Andrea Cosentino created CAMEL-24936:
----------------------------------------
Summary: camel-netty: NettyConverter.toByteArray should copy only
the readable bytes of the ByteBuf
Key: CAMEL-24936
URL: https://issues.apache.org/jira/browse/CAMEL-24936
Project: Camel
Issue Type: Improvement
Components: camel-netty
Reporter: Andrea Cosentino
Assignee: Andrea Cosentino
{code:java}
if (buffer.hasArray()) {
return buffer.array();
}
{code}
NettyConverter.toByteArray(ByteBuf, Exchange) has a fast path (above) that
returns buffer.array() directly for array-backed buffers. buffer.array()
returns the whole backing array of the ByteBuf, which does not necessarily
correspond to the buffer's readable region: it ignores arrayOffset(),
readerIndex() and readableBytes(). For array-backed buffers this can return
more bytes than the buffer actually holds (and, with shared/pooled backing
arrays, bytes outside this buffer's own slice), and it also hands out a direct
reference to a buffer that may be pooled and later reused.
The non-array branch already does the correct thing (copies exactly
readableBytes() starting at readerIndex()). The array branch should behave the
same way.
Proposed change - drop the hasArray() shortcut and always copy exactly the
readable region:
{code:java}
byte[] bytes = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), bytes);
return bytes;
{code}
This keeps the conversion consistent regardless of the underlying allocator
(heap vs direct, pooled vs unpooled) and avoids returning bytes outside the
readable region. The shared converter is also used by camel-netty-http,
camel-hl7, camel-lumberjack and camel-syslog, so the fix benefits all of them.
Add a regression test that converts an array-backed (heap) ByteBuf whose
readable region is a subset of its backing array and asserts only the readable
bytes are returned.
Affected: NettyConverter.toByteArray in camel-netty (main, 4.22.x, 4.18.x).
--
This message was sent by Atlassian Jira
(v8.20.10#820010)