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 — Support read-only input buffers in SslHandler by lhotari · Pull Request #14079 · netty/netty

Support read-only input buffers in SslHandler #14079

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lhotari wants to merge 2 commits into netty:4.1 from lhotari:lh-support-copying-readonly-input-buffer

Uh oh!

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

Closed

Support read-only input buffers in SslHandler #14079

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
9955ed0
Add support for read-only buffers in SslHandler
lhotari May 24, 2024
be948fa
Add integration tests for read-only buffers
lhotari May 27, 2024
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

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

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

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

Diff view
Diff view

There are no files selected for viewing

89 changes: 83 additions & 6 deletions 89 handler/src/main/java/io/netty/handler/ssl/SslHandler.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH
private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024;

private enum SslEngineType {
TCNATIVE(true, COMPOSITE_CUMULATOR) {
TCNATIVE(true, COMPOSITE_CUMULATOR, false) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
int nioBufferCount = in.nioBufferCount();
Expand Down Expand Up @@ -250,7 +250,7 @@ boolean jdkCompatibilityMode(SSLEngine engine) {
return ((ReferenceCountedOpenSslEngine) engine).jdkCompatibilityMode;
}
},
CONSCRYPT(true, COMPOSITE_CUMULATOR) {
CONSCRYPT(true, COMPOSITE_CUMULATOR, false) {
@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
int nioBufferCount = in.nioBufferCount();
Expand Down Expand Up @@ -299,7 +299,10 @@ boolean jdkCompatibilityMode(SSLEngine engine) {
return true;
}
},
JDK(false, MERGE_CUMULATOR) {
JDK(false, MERGE_CUMULATOR, true) {
// set wantsMutableBuffer to true for all JDKs, although JDK-8283577/JDK-8285603 is fixed since Java 19
// See: https://bugs.openjdk.org/browse/JDK-8283577

@Override
SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
int writerIndex = out.writerIndex();
Expand Down Expand Up @@ -361,9 +364,10 @@ static SslEngineType forEngine(SSLEngine engine) {
engine instanceof ConscryptAlpnSslEngine ? CONSCRYPT : JDK;
}

SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator) {
SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator, boolean wantsMutableBuffer) {
this.wantsDirectBuffer = wantsDirectBuffer;
this.cumulator = cumulator;
this.wantsMutableBuffer = wantsMutableBuffer;
}

abstract SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException;
Expand Down Expand Up @@ -396,6 +400,14 @@ abstract ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocat
* and which does not need to do extra memory copies.
*/
final Cumulator cumulator;

/**
* {@code true} if and only if {@link SSLEngine} expects a mutable buffer.
* This applies to JDK {@link SSLEngine} only and is used to determine if we need to create a copy of a
* read-only input {@link ByteBuf}. See https://bugs.openjdk.org/browse/JDK-8283577
* and https://bugs.openjdk.org/browse/JDK-8285603 for more details.
*/
final boolean wantsMutableBuffer;
}

private volatile ChannelHandlerContext ctx;
Expand Down Expand Up @@ -837,7 +849,9 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti
ChannelPromise promise = ctx.newPromise();
ByteBuf buf = wrapDataSize > 0 ?
pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) :
pendingUnencryptedWrites.removeFirst(promise);
cloneBufferIfReadOnlyAndWantsMutable(alloc, pendingUnencryptedWrites.removeFirst(promise),
engineType.wantsMutableBuffer,
engineType.wantsDirectBuffer);
if (buf == null) {
break;
}
Expand Down Expand Up @@ -951,6 +965,31 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti
}
}

static ByteBuf cloneBufferIfReadOnlyAndWantsMutable(ByteBufAllocator allocator, ByteBuf buf,
boolean wantsMutableBuffer, boolean wantsDirectBuffer) {
if (wantsMutableBuffer && buf != null && buf.isReadOnly()) {
return cloneBuffer(allocator, buf, wantsDirectBuffer);
}
return buf;
}

static ByteBuf cloneBuffer(ByteBufAllocator allocator, ByteBuf buf, boolean wantsDirectBuffer) {
ByteBuf copyOfBuf;
Comment thread
lhotari marked this conversation as resolved.
Resolved

Uh oh!

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

if (wantsDirectBuffer) {
copyOfBuf = allocator.directBuffer(buf.readableBytes());
} else {
copyOfBuf = allocator.heapBuffer(buf.readableBytes());
}
try {
copyOfBuf.writeBytes(buf);
} catch (Throwable cause) {
copyOfBuf.release();
PlatformDependent.throwException(cause);
}
buf.release();
return copyOfBuf;
}

/**
* This method will not call
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or
Expand Down Expand Up @@ -1092,6 +1131,7 @@ private SSLEngineResult wrapMultiple(ByteBufAllocator alloc, SSLEngine engine, B
private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
throws SSLException {
ByteBuf newDirectIn = null;
ByteBuf[] newMutableBuffers = null;
try {
int readerIndex = in.readerIndex();
int readableBytes = in.readableBytes();
Expand Down Expand Up @@ -1122,6 +1162,36 @@ private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf i
in0[0] = newDirectIn.internalNioBuffer(newDirectIn.readerIndex(), readableBytes);
}

// Check if the engine type wants a mutable buffer and if so replace all readonly buffers with mutable ones.
if (engineType.wantsMutableBuffer) {
// count the number of readonly buffers to avoid an extra allocation if no readonly buffers are found.
int readOnlyBufferCount = 0;
for (int i = 0; i < in0.length; i++) {
if (in0[i].isReadOnly()) {
readOnlyBufferCount++;
}
}
if (readOnlyBufferCount > 0) {
newMutableBuffers = new ByteBuf[readOnlyBufferCount];
int newMutableBufferIndex = 0;
for (int i = 0; i < in0.length; i++) {
if (in0[i].isReadOnly()) {
ByteBuffer original = in0[i];
ByteBuf copyOfNioBuffer;
if (engineType.wantsDirectBuffer) {
copyOfNioBuffer = alloc.directBuffer(original.remaining());
} else {
copyOfNioBuffer = alloc.buffer(original.remaining());
}
copyOfNioBuffer.writeBytes(original);
in0[i] = copyOfNioBuffer.internalNioBuffer(copyOfNioBuffer.readerIndex(),
copyOfNioBuffer.readableBytes());
newMutableBuffers[newMutableBufferIndex++] = copyOfNioBuffer;
}
}
}
}
Comment thread
lhotari marked this conversation as resolved.
Resolved

Uh oh!

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


for (;;) {
// Use toByteBuffer(...) which might be able to return the internal ByteBuffer and so reduce
// allocations.
Expand All @@ -1143,6 +1213,12 @@ private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf i
if (newDirectIn != null) {
newDirectIn.release();
}

if (newMutableBuffers != null) {
for (ByteBuf buf: newMutableBuffers) {
buf.release();
}
}
}
}

Expand Down Expand Up @@ -2076,7 +2152,8 @@ private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exc
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
Channel channel = ctx.channel();
pendingUnencryptedWrites = new SslHandlerCoalescingBufferQueue(channel, 16, engineType.wantsDirectBuffer) {
pendingUnencryptedWrites = new SslHandlerCoalescingBufferQueue(channel, 16, engineType.wantsDirectBuffer,
engineType.wantsMutableBuffer) {
@Override
protected int wrapDataSize() {
return SslHandler.this.wrapDataSize;
Expand Down
10 changes: 9 additions & 1 deletion 10 handler/src/main/java/io/netty/handler/ssl/SslHandlerCoalescingBufferQueue.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@
abstract class SslHandlerCoalescingBufferQueue extends AbstractCoalescingBufferQueue {

private final boolean wantsDirectBuffer;
private final boolean wantsMutableBuffer;

SslHandlerCoalescingBufferQueue(Channel channel, int initSize, boolean wantsDirectBuffer) {
SslHandlerCoalescingBufferQueue(Channel channel, int initSize, boolean wantsDirectBuffer,
boolean wantsMutableBuffer) {
super(channel, initSize);
this.wantsDirectBuffer = wantsDirectBuffer;
this.wantsMutableBuffer = wantsMutableBuffer;
}

protected abstract int wrapDataSize();
Expand Down Expand Up @@ -76,6 +79,11 @@ protected ByteBuf composeFirst(ByteBufAllocator allocator, ByteBuf first) {
return first;
}

@Override
protected ByteBuf returnFirst(ByteBufAllocator allocator, ByteBuf first) {
return SslHandler.cloneBufferIfReadOnlyAndWantsMutable(allocator, first, wantsMutableBuffer, wantsDirectBuffer);
Comment thread
lhotari marked this conversation as resolved.
Resolved

Uh oh!

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

}

@Override
protected ByteBuf removeEmptyValue() {
return null;
Expand Down
66 changes: 65 additions & 1 deletion 66 handler/src/test/java/io/netty/handler/ssl/SslHandlerCoalescingBufferQueueTest.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class SslHandlerCoalescingBufferQueueTest {
@ValueSource(booleans = { true, false })
public void testCumulation(boolean readOnlyAndDuplicate) {
EmbeddedChannel channel = new EmbeddedChannel();
SslHandlerCoalescingBufferQueue queue = new SslHandlerCoalescingBufferQueue(channel, 16, false) {
SslHandlerCoalescingBufferQueue queue = new SslHandlerCoalescingBufferQueue(channel, 16, false, false) {
@Override
protected int wrapDataSize() {
return 128;
Expand Down Expand Up @@ -73,4 +73,68 @@ protected int wrapDataSize() {
assertEquals(0, first.refCnt());
assertEquals(0, second.refCnt());
}

@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testSmallerBufferThanRequestedBytesGetsCopiedWhenWantsMutableBuffer(boolean wantsMutableBuffer) {
EmbeddedChannel channel = new EmbeddedChannel();
SslHandlerCoalescingBufferQueue queue =
new SslHandlerCoalescingBufferQueue(channel, 16, false, wantsMutableBuffer) {
@Override
protected int wrapDataSize() {
return 128;
}
};

ByteBuf buf = Unpooled.buffer(64);
buf.writeZero(64);
buf = buf.asReadOnly();
queue.add(buf);

ChannelPromise promise = channel.newPromise();
ByteBuf buffer = queue.remove(UnpooledByteBufAllocator.DEFAULT, 128, promise);
try {
assertEquals(64, buffer.readableBytes());
// Ensure that the buffer is a copy if we want a mutable buffer.
assertEquals(wantsMutableBuffer, buf != buffer);
// Ensure that the buffer is not read-only if we want a mutable buffer.
assertEquals(wantsMutableBuffer, !buffer.isReadOnly());
} finally {
buffer.release();
}
}

@ParameterizedTest
@ValueSource(booleans = { true, false })
public void testLargerBufferThanRequestedBytesGetsCopiedWhenWantsMutableBuffer(boolean wantsMutableBuffer) {
EmbeddedChannel channel = new EmbeddedChannel();
SslHandlerCoalescingBufferQueue queue =
new SslHandlerCoalescingBufferQueue(channel, 16, false, wantsMutableBuffer) {
@Override
protected int wrapDataSize() {
return 128;
}
};

ByteBuf buf = Unpooled.buffer(256);
buf.writeZero(256);
buf = buf.asReadOnly();
queue.add(buf);

ChannelPromise promise = channel.newPromise();
for (;;) {
ByteBuf buffer = queue.remove(UnpooledByteBufAllocator.DEFAULT, 128, promise);
if (buffer == null) {
break;
}
try {
assertEquals(128, buffer.readableBytes());
// Ensure that the buffer is not read-only if we want a mutable buffer.
assertEquals(wantsMutableBuffer, !buffer.isReadOnly());
} finally {
buffer.release();
}
}
assertTrue(queue.isEmpty());
}
}
Loading
Oops, something went wrong.

Uh oh!

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

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.