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 — `HttpObjectEncoder` / `DefaultHttp2FrameWriter`: fix buffer leak when… · lltopk/netty@10e24f9

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • codec-http2/src
    • main/java/io/netty/handler/codec/http2
      • DefaultHttp2FrameWriter.java
    • test/java/io/netty/handler/codec/http2
      • DefaultHttp2FrameWriterTest.java
  • codec-http/src
    • main/java/io/netty/handler/codec/http
      • HttpObjectEncoder.java
    • test/java/io/netty/handler/codec/http
      • HttpResponseEncoderTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java‎

Copy file name to clipboardExpand all lines: codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java
+34-19Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -331,19 +331,26 @@ private void encodeFullHttpMessage(ChannelHandlerContext ctx, Object o, List<Obj
331331
final int headersAndContentSize = (int) headersEncodedSizeAccumulator +
332332
(accountForContentSize? content.readableBytes() : 0);
333333
final ByteBuf buf = ctx.alloc().buffer(headersAndContentSize);
334+
boolean handedOff = false;
335+
try {
336+
encodeInitialLine(buf, m);
334337

335-
encodeInitialLine(buf, m);
336-
337-
sanitizeHeadersBeforeEncode(m, state == ST_CONTENT_ALWAYS_EMPTY);
338+
sanitizeHeadersBeforeEncode(m, state == ST_CONTENT_ALWAYS_EMPTY);
338339

339-
encodeHeaders(m.headers(), buf);
340-
ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
340+
encodeHeaders(m.headers(), buf);
341+
ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
341342

342-
// don't consider the copyContent case here: the statistics is just related the headers
343-
headersEncodedSizeAccumulator = HEADERS_WEIGHT_NEW * padSizeForAccumulation(buf.readableBytes()) +
344-
HEADERS_WEIGHT_HISTORICAL * headersEncodedSizeAccumulator;
343+
// don't consider the copyContent case here: the statistics is just related the headers
344+
headersEncodedSizeAccumulator = HEADERS_WEIGHT_NEW * padSizeForAccumulation(buf.readableBytes()) +
345+
HEADERS_WEIGHT_HISTORICAL * headersEncodedSizeAccumulator;
345346

346-
encodeByteBufHttpContent(state, ctx, buf, content, msg.trailingHeaders(), out);
347+
handedOff = true;
348+
encodeByteBufHttpContent(state, ctx, buf, content, msg.trailingHeaders(), out);
349+
} finally {
350+
if (!handedOff) {
351+
buf.release();
352+
}
353+
}
347354
} finally {
348355
msg.release();
349356
}
@@ -521,19 +528,27 @@ private ByteBuf encodeInitHttpMessage(ChannelHandlerContext ctx, H m) throws Exc
521528
assert state == ST_INIT;
522529

523530
ByteBuf buf = ctx.alloc().buffer((int) headersEncodedSizeAccumulator);
524-
// Encode the message.
525-
encodeInitialLine(buf, m);
526-
state = isContentAlwaysEmpty(m) ? ST_CONTENT_ALWAYS_EMPTY :
527-
HttpUtil.isTransferEncodingChunked(m) ? ST_CONTENT_CHUNK : ST_CONTENT_NON_CHUNK;
531+
boolean success = false;
532+
try {
533+
// Encode the message.
534+
encodeInitialLine(buf, m);
535+
state = isContentAlwaysEmpty(m) ? ST_CONTENT_ALWAYS_EMPTY :
536+
HttpUtil.isTransferEncodingChunked(m) ? ST_CONTENT_CHUNK : ST_CONTENT_NON_CHUNK;
528537

529-
sanitizeHeadersBeforeEncode(m, state == ST_CONTENT_ALWAYS_EMPTY);
538+
sanitizeHeadersBeforeEncode(m, state == ST_CONTENT_ALWAYS_EMPTY);
530539

531-
encodeHeaders(m.headers(), buf);
532-
ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
540+
encodeHeaders(m.headers(), buf);
541+
ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
533542

534-
headersEncodedSizeAccumulator = HEADERS_WEIGHT_NEW * padSizeForAccumulation(buf.readableBytes()) +
535-
HEADERS_WEIGHT_HISTORICAL * headersEncodedSizeAccumulator;
536-
return buf;
543+
headersEncodedSizeAccumulator = HEADERS_WEIGHT_NEW * padSizeForAccumulation(buf.readableBytes()) +
544+
HEADERS_WEIGHT_HISTORICAL * headersEncodedSizeAccumulator;
545+
success = true;
546+
return buf;
547+
} finally {
548+
if (!success) {
549+
buf.release();
550+
}
551+
}
537552
}
538553

539554
/**
Collapse file

‎codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java‎

Copy file name to clipboardExpand all lines: codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java
+164Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,31 @@
1515
*/
1616
package io.netty.handler.codec.http;
1717

18+
import io.netty.buffer.AbstractByteBufAllocator;
1819
import io.netty.buffer.ByteBuf;
20+
import io.netty.buffer.ByteBufAllocator;
21+
import io.netty.buffer.UnpooledByteBufAllocator;
1922
import io.netty.buffer.Unpooled;
2023
import io.netty.channel.FileRegion;
2124
import io.netty.channel.embedded.EmbeddedChannel;
25+
import io.netty.handler.codec.EncoderException;
2226
import io.netty.util.CharsetUtil;
2327
import org.junit.jupiter.api.Test;
28+
import org.junit.jupiter.api.function.Executable;
2429

2530
import java.io.IOException;
2631
import java.nio.channels.WritableByteChannel;
32+
import java.util.ArrayList;
33+
import java.util.Iterator;
34+
import java.util.List;
35+
import java.util.Map.Entry;
36+
import java.util.concurrent.ExecutionException;
2737

2838
import static org.junit.jupiter.api.Assertions.assertEquals;
2939
import static org.junit.jupiter.api.Assertions.assertFalse;
40+
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
3041
import static org.junit.jupiter.api.Assertions.assertSame;
42+
import static org.junit.jupiter.api.Assertions.assertThrows;
3143
import static org.junit.jupiter.api.Assertions.assertTrue;
3244

3345
public class HttpResponseEncoderTest {
@@ -399,4 +411,156 @@ private static void testStatusResetContentTransferContentLength0(CharSequence he
399411
assertEquals(responseText.toString(), written.toString());
400412
assertFalse(channel.finish());
401413
}
414+
415+
@Test
416+
public void testInitHttpMessageHeaderEncodingFailureReleasesBuffer() throws Exception {
417+
final TrackingFailingAllocator allocator = new TrackingFailingAllocator();
418+
final EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
419+
channel.config().setAllocator(allocator);
420+
421+
final DefaultHttpResponse response =
422+
new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new ThrowingHeaders());
423+
424+
ExecutionException e = assertThrows(ExecutionException.class, new Executable() {
425+
@Override
426+
public void execute() throws Throwable {
427+
channel.writeAndFlush(response).get();
428+
}
429+
});
430+
assertInstanceOf(EncoderException.class, e.getCause());
431+
assertInstanceOf(OutOfMemoryError.class, e.getCause().getCause());
432+
433+
assertAllTrackedBuffersReleased(allocator);
434+
channel.finishAndReleaseAll();
435+
}
436+
437+
@Test
438+
public void testFullHttpMessageHeaderEncodingFailureReleasesBuffer() throws Exception {
439+
final TrackingFailingAllocator allocator = new TrackingFailingAllocator();
440+
final EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
441+
channel.config().setAllocator(allocator);
442+
443+
final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
444+
HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER, new ThrowingHeaders(), new DefaultHttpHeaders());
445+
446+
ExecutionException e = assertThrows(ExecutionException.class, new Executable() {
447+
@Override
448+
public void execute() throws Throwable {
449+
channel.writeAndFlush(response).get();
450+
}
451+
});
452+
assertInstanceOf(EncoderException.class, e.getCause());
453+
assertInstanceOf(OutOfMemoryError.class, e.getCause().getCause());
454+
455+
assertAllTrackedBuffersReleased(allocator);
456+
channel.finishAndReleaseAll();
457+
}
458+
459+
@Test
460+
public void testChunkedContentLengthAllocationFailureDoesNotDoubleReleaseHeaderBuffer() throws Exception {
461+
final TrackingFailingAllocator allocator = new TrackingFailingAllocator(3);
462+
final EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder());
463+
channel.config().setAllocator(allocator);
464+
465+
final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
466+
HttpResponseStatus.OK, Unpooled.copiedBuffer("1", CharsetUtil.US_ASCII));
467+
HttpUtil.setTransferEncodingChunked(response, true);
468+
469+
EncoderException e = assertThrows(EncoderException.class, new Executable() {
470+
@Override
471+
public void execute() throws Throwable {
472+
channel.writeOutbound(response);
473+
}
474+
});
475+
assertInstanceOf(OutOfMemoryError.class, e.getCause());
476+
477+
for (;;) {
478+
ByteBuf buf = channel.readOutbound();
479+
if (buf == null) {
480+
break;
481+
}
482+
buf.release();
483+
}
484+
485+
assertAllTrackedBuffersReleased(allocator);
486+
channel.finishAndReleaseAll();
487+
}
488+
489+
private static void assertAllTrackedBuffersReleased(TrackingFailingAllocator allocator) {
490+
assertFalse(allocator.allocated.isEmpty(), "expected at least one buffer to be allocated");
491+
for (ByteBuf buf : allocator.allocated) {
492+
assertEquals(0, buf.refCnt(), "expected tracked buffer to be released: " + buf);
493+
}
494+
}
495+
496+
/**
497+
* A {@link ByteBufAllocator} that throws an {@link OutOfMemoryError} when asked to allocate a buffer with a
498+
* given {@code initialCapacity}, and otherwise delegates to an unpooled allocator while tracking every
499+
* successfully allocated buffer for leak verification.
500+
*/
501+
private static final class TrackingFailingAllocator extends AbstractByteBufAllocator {
502+
private static final int NEVER_FAIL = -1;
503+
504+
private final ByteBufAllocator delegate = new UnpooledByteBufAllocator(false);
505+
private final List<ByteBuf> allocated = new ArrayList<ByteBuf>();
506+
private final int failOnInitialCapacity;
507+
508+
TrackingFailingAllocator() {
509+
this(NEVER_FAIL);
510+
}
511+
512+
TrackingFailingAllocator(int failOnInitialCapacity) {
513+
super(false);
514+
this.failOnInitialCapacity = failOnInitialCapacity;
515+
}
516+
517+
private void failIfTargeted(int initialCapacity) {
518+
if (failOnInitialCapacity != NEVER_FAIL && initialCapacity == failOnInitialCapacity) {
519+
throw new OutOfMemoryError("simulated allocation failure for capacity " + initialCapacity);
520+
}
521+
}
522+
523+
@Override
524+
protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
525+
failIfTargeted(initialCapacity);
526+
ByteBuf buf = delegate.heapBuffer(initialCapacity, maxCapacity);
527+
allocated.add(buf);
528+
return buf;
529+
}
530+
531+
@Override
532+
protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
533+
failIfTargeted(initialCapacity);
534+
ByteBuf buf = delegate.directBuffer(initialCapacity, maxCapacity);
535+
allocated.add(buf);
536+
return buf;
537+
}
538+
539+
@Override
540+
public boolean isDirectBufferPooled() {
541+
return delegate.isDirectBufferPooled();
542+
}
543+
}
544+
545+
private static final class ThrowingHeaders extends DefaultHttpHeaders {
546+
@Override
547+
public Iterator<Entry<CharSequence, CharSequence>> iteratorCharSequence() {
548+
return new Iterator<Entry<CharSequence, CharSequence>>() {
549+
@Override
550+
public boolean hasNext() {
551+
return true;
552+
}
553+
554+
@Override
555+
public Entry<CharSequence, CharSequence> next() {
556+
throw new OutOfMemoryError("simulated header encoding failure");
557+
}
558+
559+
@Override
560+
public void remove() {
561+
throw new UnsupportedOperationException();
562+
}
563+
};
564+
}
565+
}
402566
}

0 commit comments

Comments
0 (0)
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.