instance_id
stringlengths
17
39
repo
stringclasses
8 values
issue_id
stringlengths
14
34
pr_id
stringlengths
14
34
linking_methods
sequencelengths
1
3
base_commit
stringlengths
40
40
merge_commit
stringlengths
0
40
hints_text
sequencelengths
0
106
resolved_comments
sequencelengths
0
119
created_at
unknown
labeled_as
sequencelengths
0
7
problem_title
stringlengths
7
174
problem_statement
stringlengths
0
55.4k
gold_files
sequencelengths
0
10
gold_files_postpatch
sequencelengths
1
10
test_files
sequencelengths
0
60
gold_patch
stringlengths
220
5.83M
test_patch
stringlengths
386
194k
split_random
stringclasses
3 values
split_time
stringclasses
3 values
issue_start_time
unknown
issue_created_at
unknown
issue_by_user
stringlengths
3
21
split_repo
stringclasses
3 values
netty/netty/6628_6635
netty/netty
netty/netty/6628
netty/netty/6635
[ "timestamp(timedelta=108971.0, similarity=0.8467740071384211)" ]
cc5d1d0a7e6475c6dc3628321c17a62785016163
59e95c98afa10568327d2678c4e1c65f99131041
[ "Fixed... we now also deploy the OS X snapshot version", "Which remote repository will upload? Is it only sonatype-nexus?", "https://oss.sonatype.org/content/repositories/snapshots/io/netty/netty-tcnative/2.0.1.Final-SNAPSHOT/\r\n\r\nWe will release a final version this week tho", "At this time ,the final version is not release.", "@qiaodaimadelaowang it is... Why you say otherwise ?\r\n\r\nhttp://repo1.maven.org/maven2/io/netty/netty-tcnative/2.0.1.Final/", "Sorry.", "Final version in http://repo1.maven.org/maven2/io/netty/netty-tcnative/\r\nand SNAPSHOT in https://oss.sonatype.org/content/repositories/snapshots/io/netty/netty-tcnative ?", "Yes\n\n> Am 28.04.2017 um 12:08 schrieb tinyhui.wang <notifications@github.com>:\n> \n> Final version in http://repo1.maven.org/maven2/io/netty/netty-tcnative/\n> and SNAPSHOT in https://oss.sonatype.org/content/repositories/snapshots/io/netty/netty-tcnative ?\n> \n> —\n> You are receiving this because you modified the open/close state.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n" ]
[]
"2017-04-18T08:14:00Z"
[]
Could not find artifact io.netty:netty-tcnative:jar:osx-x86_64:2.0.1.Final-SNAPSHOT
### Expected behavior mvn -s ~/.m2/settings_default.xml package is ok. ### Actual behavior Could not find artifact io.netty:netty-tcnative:jar:osx-x86_64:2.0.1.Final-SNAPSHOT ### Steps to reproduce 1.git clone https://github.com/netty/netty.git 2.mvn -s ~/.m2/settings_default.xml package ### Minimal yet complete reproducer code (or URL to code) ### Netty version latest source code on 4.1 branch ### JVM version (e.g. `java -version`) java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) ### OS version (e.g. `uname -a`) Darwin tinyhuiwang 16.5.0 Darwin Kernel Version 16.5.0: Fri Mar 3 16:52:33 PST 2017; root:xnu-3789.51.2~3/RELEASE_X86_64 x86_64 i386 MacBookPro12,1 Darwin ### others I found in pom.xml(netty-parent),the tcnative.version is 2.0.1.Final-SNAPSHOT,but in http://repo1.maven.org/maven2/io/netty/netty-tcnative/ ,can not find this version ,only 2.0.0,and not SNAPSHOT.
[ "pom.xml" ]
[ "pom.xml" ]
[]
diff --git a/pom.xml b/pom.xml index a2ebfb0ce6d..86d54c3ce3f 100644 --- a/pom.xml +++ b/pom.xml @@ -242,7 +242,7 @@ <!-- Fedora-"like" systems. This is currently only used for the netty-tcnative dependency --> <os.detection.classifierWithLikes>fedora</os.detection.classifierWithLikes> <tcnative.artifactId>netty-tcnative</tcnative.artifactId> - <tcnative.version>2.0.1.Final-SNAPSHOT</tcnative.version> + <tcnative.version>2.0.1.Final</tcnative.version> <tcnative.classifier>${os.detected.classifier}</tcnative.classifier> <conscrypt.groupId>org.conscrypt</conscrypt.groupId> <conscrypt.artifactId>conscrypt-openjdk-uber</conscrypt.artifactId>
null
train
train
"2017-04-18T08:16:33"
"2017-04-16T02:06:12Z"
typercode
val
netty/netty/6577_6636
netty/netty
netty/netty/6577
netty/netty/6636
[ "timestamp(timedelta=51941.0, similarity=0.8466659931370951)" ]
cc5d1d0a7e6475c6dc3628321c17a62785016163
0babef24a9a63282eb9d0aec570b99a1639bd723
[ "from https://github.com/netty/netty/pull/6601#issuecomment-291454620\r\n\r\n<details><pre><code>\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] 09:17:00.076 [main] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Recent access records: 7\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #7:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #6:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #5:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.toString(AdvancedLeakAwareByteBuf.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.processGoAwayWriteResult(Http2ConnectionHandler.java:849)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.access$1100(Http2ConnectionHandler.java:66)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$4.operationComplete(Http2ConnectionHandler.java:777)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$4.operationComplete(Http2ConnectionHandler.java:774)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:500)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:479)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.tryPromise(Http2CodecUtil.java:384)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.trySuccess(Http2CodecUtil.java:350)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.trySuccess(Http2CodecUtil.java:262)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.internal.PromiseNotificationUtil.trySuccess(PromiseNotificationUtil.java:48)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.ChannelOutboundBuffer.safeSuccess(ChannelOutboundBuffer.java:668)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.ChannelOutboundBuffer.remove(ChannelOutboundBuffer.java:257)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:362)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #4:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #3:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:367)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #2:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:768)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #1:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.ensureWritable(AdvancedLeakAwareByteBuf.java:132)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:427)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:415)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.toByteBuf(Http2CodecUtil.java:198)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:414)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.toByteBuf(Http2CodecUtil.java:198)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] 09:17:00.077 [main] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Recent access records: 10\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #10:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #9:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #8:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #7:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #6:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:363)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #5:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:362)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #4:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:255)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #3:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:254)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #2:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:253)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #1:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeMedium(AdvancedLeakAwareByteBuf.java:552)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:252)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:360)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] 09:17:00.078 [main] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Recent access records: 10\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #10:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #9:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #8:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #7:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:249)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #6:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:247)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #5:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeChar(AdvancedLeakAwareByteBuf.java:570)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:246)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #4:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:255)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #3:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:254)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #2:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:253)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] #1:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeMedium(AdvancedLeakAwareByteBuf.java:552)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:252)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:243)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[09:17:00] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n</code></pre></details>", "During CI build of PR https://github.com/netty/netty/pull/6608\r\n\r\nhttps://garage.netty.io/teamcity/viewLog.html?buildId=18911&buildTypeId=pulls_netty&guest=1\r\n\r\n```\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] 18:16:48.062 [nioEventLoopGroup-35-1] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Recent access records: 10\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #10:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #9:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #8:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #7:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #6:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:363)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #5:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:362)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #4:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:255)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #3:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:254)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #2:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:253)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #1:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeMedium(AdvancedLeakAwareByteBuf.java:552)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:252)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:360)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] 18:16:48.064 [nioEventLoopGroup-35-1] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Recent access records: 10\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #10:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #9:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #8:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #7:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:249)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #6:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:247)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #5:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeChar(AdvancedLeakAwareByteBuf.java:570)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:246)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #4:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:255)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #3:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:254)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #2:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:253)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #1:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.writeMedium(AdvancedLeakAwareByteBuf.java:552)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:252)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:244)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeSettings(DefaultHttp2FrameWriter.java:243)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writeSettings(DefaultHttp2ConnectionEncoder.java:239)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.sendPreface(Http2ConnectionHandler.java:344)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$PrefaceDecoder.channelActive(Http2ConnectionHandler.java:234)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.channelActive(Http2ConnectionHandler.java:383)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:192)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1322)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:213)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:902)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$3.run(LocalChannel.java:199)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] 18:16:48.075 [nioEventLoopGroup-35-1] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Recent access records: 7\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #7:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'HttpToHttp2ConnectionHandler#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #6:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead0(LocalChannel.java:443)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.finishPeerRead(LocalChannel.java:385)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doClose(LocalChannel.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:685)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.tryClose(LocalChannel.java:283)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.access$400(LocalChannel.java:49)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel$4.run(LocalChannel.java:261)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #5:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.toString(AdvancedLeakAwareByteBuf.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.processGoAwayWriteResult(Http2ConnectionHandler.java:849)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.access$1100(Http2ConnectionHandler.java:66)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$4.operationComplete(Http2ConnectionHandler.java:777)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler$4.operationComplete(Http2ConnectionHandler.java:774)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:500)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:479)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.tryPromise(Http2CodecUtil.java:384)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.trySuccess(Http2CodecUtil.java:350)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator.trySuccess(Http2CodecUtil.java:262)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.internal.PromiseNotificationUtil.trySuccess(PromiseNotificationUtil.java:48)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.ChannelOutboundBuffer.safeSuccess(ChannelOutboundBuffer.java:668)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.ChannelOutboundBuffer.remove(ChannelOutboundBuffer.java:257)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:362)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #4:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:573)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #3:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tHint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point.\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:367)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #2:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:768)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] #1:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AdvancedLeakAwareByteBuf.ensureWritable(AdvancedLeakAwareByteBuf.java:132)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:427)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:415)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.toByteBuf(Http2CodecUtil.java:198)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] Created at:\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.buffer.ByteBufUtil.writeUtf8(ByteBufUtil.java:414)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2CodecUtil.toByteBuf(Http2CodecUtil.java:198)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onConnectionError(Http2ConnectionHandler.java:600)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.Http2ConnectionHandler.onError(Http2ConnectionHandler.java:571)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.handler.codec.http2.HttpToHttp2ConnectionHandler.write(HttpToHttp2ConnectionHandler.java:115)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext.access$1900(AbstractChannelHandlerContext.java:38)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.write(AbstractChannelHandlerContext.java:1089)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$WriteAndFlushTask.write(AbstractChannelHandlerContext.java:1136)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.AbstractChannelHandlerContext$AbstractWriteTask.run(AbstractChannelHandlerContext.java:1078)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tio.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)\r\n[18:16:48] :\t\t [io.netty:netty-codec-http2] \tjava.lang.Thread.run(Thread.java:745)\r\n```", "From PR https://github.com/netty/netty/pull/6614\r\n> I have investigated this in the past, but don't have time to dig in now. It seems that the writes are making it to the LocalChannel and therefore the LocalChannel is responsible for releasing the objects. This PR shouldn't make anything worse so I will merge it as a stop gap until I have more time to investigate.", "I think this might related to #6639.\r\nHere is my findings.\r\n\r\nI think the test have memory leak problem might be [HttpToHttp2ConnectionHandlerTest.java#L319-L334](https://github.com/netty/netty/blob/4.1/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpToHttp2ConnectionHandlerTest.java#L319-L334).\r\nAnd maybe other tests had similar problems.\r\n\r\nIt happens when server channel fire his first channel read when channel is inactive, but client channel had already sent connection preface and frames. And the ByteToMessageDecoder will try append the frames' ByteBuf into connection preface(an unreleasable ByteBuf) but failed and leak.\r\n\r\nHere is the steps when the memory leak happen\r\n- clientChannel write connection preface\r\n- clientChannel write GOAWAY\r\n- clientChannel close\r\n- serverChannel read connection preface but failed because the channel is inactive, then the connection preface become cumulation of ByteToMessageDecoder at [Http2ConnectionHandler.java#L221](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java#L221) and [ByteToMessageDecoder.java#L244](https://github.com/netty/netty/blob/4.1/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java#L244)\r\n- serverChannel read GOAWAY ByteBuf into cumulation but failed <= memory leak happen at [ByteToMessageDecoder.java#L92](https://github.com/netty/netty/blob/4.1/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java#L92) <= It will throw Exception and leak", "@chhsiao90 yes I think so too. Let me close this one as fixed by https://github.com/netty/netty/pull/6639" ]
[]
"2017-04-18T09:17:40Z"
[ "defect" ]
HTTP/2 unit test LocalChannel ByteBuf leak
Leak observed on the CI servers while building PR #6000 CI build: https://garage.netty.io/teamcity/viewLog.html?buildId=18539&buildTypeId=pulls_netty&tab=buildLog Related: https://github.com/netty/netty/issues/5850 ``` [03:28:18] : [io.netty:netty-codec-http2] java.nio.channels.ClosedChannelException: null [03:28:18] : [io.netty:netty-codec-http2] at io.netty.channel.local.LocalChannel.doWrite(...)(Unknown Source) [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.339 [defaultEventLoopGroup-54-2] DEBUG io.netty.buffer.PoolThreadCache - Freed 6 thread-local buffer(s) from thread: defaultEventLoopGroup-54-2 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.340 [defaultEventLoopGroup-55-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 2 thread-local buffer(s) from thread: defaultEventLoopGroup-55-1 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.369 [defaultEventLoopGroup-56-2] DEBUG io.netty.buffer.PoolThreadCache - Freed 6 thread-local buffer(s) from thread: defaultEventLoopGroup-56-2 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.396 [defaultEventLoopGroup-57-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 4 thread-local buffer(s) from thread: defaultEventLoopGroup-57-1 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.433 [defaultEventLoopGroup-58-2] DEBUG io.netty.buffer.PoolThreadCache - Freed 7 thread-local buffer(s) from thread: defaultEventLoopGroup-58-2 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.439 [defaultEventLoopGroup-59-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 5 thread-local buffer(s) from thread: defaultEventLoopGroup-59-1 [03:28:18] : [io.netty:netty-codec-http2] Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.746 sec - in io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterTest [03:28:18] : [io.netty:netty-codec-http2] Running io.netty.handler.codec.http2.DataCompressionHttp2Test [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.449 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.449 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.450 [main] DEBUG i.n.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.710 [nioEventLoopGroup-62-1] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information. [03:28:18] : [io.netty:netty-codec-http2] Recent access records: 11 [03:28:18] : [io.netty:netty-codec-http2] #11: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:924) [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.retain(AdvancedLeakAwareByteBuf.java:35) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.ReferenceCountUtil.retain(ReferenceCountUtil.java:36) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.local.LocalChannel.doWrite(LocalChannel.java:361) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:856) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:823) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1296) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:447) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #10: [03:28:18] : [io.netty:netty-codec-http2] Hint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point. [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:107) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:367) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #9: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedInt(Http2CodecUtil.java:216) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:366) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #8: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedInt(Http2CodecUtil.java:215) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:366) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #7: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedInt(Http2CodecUtil.java:214) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:366) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #6: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeUnsignedInt(Http2CodecUtil.java:213) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:366) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #5: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:365) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #4: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeInt(AdvancedLeakAwareByteBuf.java:558) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:274) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #3: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:273) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #2: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeByte(AdvancedLeakAwareByteBuf.java:540) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:272) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] #1: [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AdvancedLeakAwareByteBuf.writeMedium(AdvancedLeakAwareByteBuf.java:552) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeaderInternal(Http2CodecUtil.java:271) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:364) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] Created at: [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.ResourceLeakDetector.track(ResourceLeakDetector.java:237) [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.PooledByteBufAllocator.newHeapBuffer(PooledByteBufAllocator.java:310) [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:162) [03:28:18] : [io.netty:netty-codec-http2] io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:153) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.local.PreferHeapByteBufAllocator.buffer(PreferHeapByteBufAllocator.java:40) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writeGoAway(DefaultHttp2FrameWriter.java:363) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:769) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.goAway(Http2ConnectionHandler.java:816) [03:28:18] : [io.netty:netty-codec-http2] io.netty.handler.codec.http2.Http2ConnectionHandler.close(Http2ConnectionHandler.java:446) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext.access$1100(AbstractChannelHandlerContext.java:38) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.AbstractChannelHandlerContext$13.run(AbstractChannelHandlerContext.java:613) [03:28:18] : [io.netty:netty-codec-http2] io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [03:28:18] : [io.netty:netty-codec-http2] io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [03:28:18] : [io.netty:netty-codec-http2] java.lang.Thread.run(Thread.java:745) [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.719 [nioEventLoopGroup-62-1] DEBUG i.n.h.c.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibDecoder: false [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.719 [nioEventLoopGroup-62-1] DEBUG i.n.h.c.compression.ZlibCodecFactory - -Dio.netty.noJdkZlibEncoder: false [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.775 [nioEventLoopGroup-61-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 6 thread-local buffer(s) from thread: nioEventLoopGroup-61-1 [03:28:18] : [io.netty:netty-codec-http2] 03:28:18.778 [nioEventLoopGroup-62-1] DEBUG io.netty.buffer.PoolThreadCache - Freed 8 thread-local buffer(s) from thread: nioEventLoopGroup-62-1 [03:28:18]i: [io.netty:netty-codec-http2] io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterTest [03:28:18]i: [io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterTest] clientRequestSingleHeaderNonAsciiShouldThrow ```
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java" ]
[]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java index d288e196a6d..0ed847f59d6 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java @@ -359,7 +359,7 @@ public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) { - Http2DataFrame dataFrame = new DefaultHttp2DataFrame(data.retain(), endOfStream, padding); + Http2DataFrame dataFrame = new DefaultHttp2DataFrame(data, endOfStream, padding); dataFrame.streamId(streamId); ctx.fireChannelRead(dataFrame);
null
train
train
"2017-04-18T08:16:33"
"2017-03-28T17:08:48Z"
Scottmitch
val
netty/netty/6657_6658
netty/netty
netty/netty/6657
netty/netty/6658
[ "timestamp(timedelta=24.0, similarity=0.8852732037586727)" ]
799350c369e68462b61c6aef97db2a33ea937434
06ecb915bdff4e83baa7d041bbb65cb20c7a78fb
[ "Fixed by https://github.com/netty/netty/pull/6658" ]
[]
"2017-04-22T17:19:45Z"
[ "defect" ]
IpSubnetFilterRule throws ClassCastException when non expected IP version comes
### Expected behavior No error. `IpSubnetFilterRule.match` returns false. ### Actual behavior `IpSubnetFilterRule.match` throws `ClassCastException`. ### Steps to reproduce ``` IpSubnetFilterRule rule = new IpSubnetFilterRule("0.0.0.0", 0, IpFilterRuleType.ACCEPT); //remoteAddress.getAddress() instanceof Inet6Address rule.matches(remoteAddress); //throws ClassCastException ``` ### Minimal yet complete reproducer code (or URL to code) ``` @Test public void testIpv4SubnetMaskCorrectlyHandlesIpv6() { IpSubnetFilterRule rule = new IpSubnetFilterRule("0.0.0.0", 0, IpFilterRuleType.ACCEPT); Assert.assertFalse(rule.matches(newSockAddress("2001:db8:abcd:0000::1"))); } ``` ### Netty version 4.1.9-Final
[ "handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java" ]
[ "handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java" ]
[ "handler/src/test/java/io/netty/handler/ipfilter/IpSubnetFilterTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java b/handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java index abcb150687f..b6c2e83ebca 100644 --- a/handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java +++ b/handler/src/main/java/io/netty/handler/ipfilter/IpSubnetFilterRule.java @@ -91,9 +91,12 @@ private Ip4SubnetFilterRule(Inet4Address ipAddress, int cidrPrefix, IpFilterRule @Override public boolean matches(InetSocketAddress remoteAddress) { - int ipAddress = ipToInt((Inet4Address) remoteAddress.getAddress()); - - return (ipAddress & subnetMask) == networkAddress; + final InetAddress inetAddress = remoteAddress.getAddress(); + if (inetAddress instanceof Inet4Address) { + int ipAddress = ipToInt((Inet4Address) inetAddress); + return (ipAddress & subnetMask) == networkAddress; + } + return false; } @Override @@ -147,9 +150,12 @@ private Ip6SubnetFilterRule(Inet6Address ipAddress, int cidrPrefix, IpFilterRule @Override public boolean matches(InetSocketAddress remoteAddress) { - BigInteger ipAddress = ipToInt((Inet6Address) remoteAddress.getAddress()); - - return ipAddress.and(subnetMask).equals(networkAddress); + final InetAddress inetAddress = remoteAddress.getAddress(); + if (inetAddress instanceof Inet6Address) { + BigInteger ipAddress = ipToInt((Inet6Address) inetAddress); + return ipAddress.and(subnetMask).equals(networkAddress); + } + return false; } @Override
diff --git a/handler/src/test/java/io/netty/handler/ipfilter/IpSubnetFilterTest.java b/handler/src/test/java/io/netty/handler/ipfilter/IpSubnetFilterTest.java index e93908b67cf..0be4cab797d 100644 --- a/handler/src/test/java/io/netty/handler/ipfilter/IpSubnetFilterTest.java +++ b/handler/src/test/java/io/netty/handler/ipfilter/IpSubnetFilterTest.java @@ -38,6 +38,18 @@ public void testIpv4DefaultRoute() { Assert.assertTrue(rule.matches(newSockAddress("192.168.93.2"))); } + @Test + public void testIpv4SubnetMaskCorrectlyHandlesIpv6() { + IpSubnetFilterRule rule = new IpSubnetFilterRule("0.0.0.0", 0, IpFilterRuleType.ACCEPT); + Assert.assertFalse(rule.matches(newSockAddress("2001:db8:abcd:0000::1"))); + } + + @Test + public void testIpv6SubnetMaskCorrectlyHandlesIpv4() { + IpSubnetFilterRule rule = new IpSubnetFilterRule("::", 0, IpFilterRuleType.ACCEPT); + Assert.assertFalse(rule.matches(newSockAddress("91.114.240.43"))); + } + @Test public void testIp4SubnetFilterRule() throws Exception { IpSubnetFilterRule rule = new IpSubnetFilterRule("192.168.56.1", 24, IpFilterRuleType.ACCEPT);
val
train
"2017-04-22T17:26:47"
"2017-04-22T17:08:43Z"
doom369
val
netty/netty/6674_6676
netty/netty
netty/netty/6674
netty/netty/6676
[ "timestamp(timedelta=26.0, similarity=1.0000000000000002)" ]
57d3393527a9dba78eda4365eae13c655e7b3f28
20c2891e8cfab711ac415e37a74cee672ad48c6b
[ "I'll fix this as it was my doing.", "@snicoll by removing the reference to the parent the version of the bom artifact is no longer updated when the version is bumped via Maven plugins, I will check into this soon.", "@johnou you can use the `oss-parent` (you'll have to add a few more details to the pom so that you can publish it to Maven central anyway).", "@jasontedor I see that the recent artifact you contributed (netty-dev-tools) uses oss-parent instead of netty-parent, do you know if the artifact version for netty-dev-tools will be incremented as part of the release / deploy cycle? At least with my local tests using versions:set -DnewVersion=.. it is not updated.", "to answer myself I believe the answer is yes, just tested with the following.. mvn --batch-mode release:update-versions -DdevelopmentVersion=4.1.11.Final-SNAPSHOT\r\n", "Yes, you got it.", "Fixed by https://github.com/netty/netty/pull/6676" ]
[ "According to [this page](https://maven.apache.org/guides/mini/guide-central-repository-upload.html) you need to add the `<url>`, `<license>` and `<scm>` tags to be able to deploy it to Maven central. Check the sample BOM in the related issue for reference.", "roger." ]
"2017-04-27T10:04:09Z"
[ "defect" ]
Netty BOM inherit from parent and its own dependency management
A BOM was recently added in #5994 but is not valid. A BOM should only expose dependency management for the artifacts that the project produces (so in this case, netty artifacts). It should not have an opinion about third party dependencies (otherwise including that BOM in a project potentially overrides decisions that were made about them). One way to fix that would be to stop inheriting from `netty-parent`. Also, I'd set the version of each dependency in the bom rather than using `${project.version}`. If you're including the bom for netty X.Y.Z, it should be X.Y.Z. and nothing else (Maven does not allow to override that property, which is good so it's not strictly necessary but the intent is more clear if you hardcode the current version). Here is an example of BOM for reference: http://repo.spring.io/release/org/springframework/spring-framework-bom/4.3.8.RELEASE/spring-framework-bom-4.3.8.RELEASE.pom We'd like to [use this bom in Spring Boot](https://github.com/spring-projects/spring-boot/issues/8553) but we can't for that reason.
[ "bom/pom.xml" ]
[ "bom/pom.xml" ]
[]
diff --git a/bom/pom.xml b/bom/pom.xml index dd72ee32e99..88d00a71cdb 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -15,136 +15,176 @@ ~ under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> <parent> - <groupId>io.netty</groupId> - <artifactId>netty-parent</artifactId> - <version>4.1.10.Final-SNAPSHOT</version> + <groupId>org.sonatype.oss</groupId> + <artifactId>oss-parent</artifactId> + <version>7</version> + <relativePath /> </parent> + <groupId>io.netty</groupId> <artifactId>netty-bom</artifactId> + <version>4.1.10.Final-SNAPSHOT</version> <packaging>pom</packaging> <name>Netty/BOM</name> + <description>Netty (Bill of Materials)</description> + <url>http://netty.io/</url> + + <organization> + <name>The Netty Project</name> + <url>http://netty.io/</url> + </organization> + + <licenses> + <license> + <name>Apache License, Version 2.0</name> + <url>http://www.apache.org/licenses/LICENSE-2.0</url> + </license> + </licenses> + <inceptionYear>2008</inceptionYear> + + <scm> + <url>https://github.com/netty/netty</url> + <connection>scm:git:git://github.com/netty/netty.git</connection> + <developerConnection>scm:git:ssh://git@github.com/netty/netty.git</developerConnection> + <tag>HEAD</tag> + </scm> + + <developers> + <developer> + <id>netty.io</id> + <name>The Netty Project Contributors</name> + <email>netty@googlegroups.com</email> + <url>http://netty.io/</url> + <organization>The Netty Project</organization> + <organizationUrl>http://netty.io/</organizationUrl> + </developer> + </developers> <dependencyManagement> <dependencies> <!-- All release modules --> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-buffer</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-dns</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-haproxy</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-http</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-http2</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-memcache</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-mqtt</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-redis</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-smtp</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-socks</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-stomp</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-codec-xml</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-common</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-handler</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-handler-proxy</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-resolver</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-resolver-dns</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-transport</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-transport-rxtx</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-transport-sctp</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-transport-udt</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> + <groupId>io.netty</groupId> <artifactId>netty-example</artifactId> - <version>${project.version}</version> + <version>4.1.10.Final-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>io.netty</groupId> + <artifactId>netty-all</artifactId> + <version>4.1.10.Final-SNAPSHOT</version> </dependency> </dependencies> </dependencyManagement>
null
train
train
"2017-04-27T04:05:16"
"2017-04-26T09:29:16Z"
snicoll
val
netty/netty/3063_6688
netty/netty
netty/netty/3063
netty/netty/6688
[ "timestamp(timedelta=24.0, similarity=0.8425311106642784)" ]
6915ec3bb9f5ff20ca8a3ac9264117d208dc4ab7
9bbe9c1c87a76dcce9eb09dd301f54b7501bfb69
[ "Investigating more on this issue, I found out that due to the channel being closed right after sending the `CloseWebSocketFrame`, the client is unable to process the `CloseWebSocketFrame`, rising an `Exception` while trying to process it (as far as I'm able to reason). I have, both in the client and the server, an `ActivityLoggingHandler` that logs the channel activity using SLF4J (without breaking the events flow through the pipeline). The exception thrown is this:\n\n```\n17:42:57.136 [nioEventLoopGroup-2-1] WARN e.u.t.r.s.c.c.ActivityLoggingHandler - Caught exception procesing data from server /127.0.0.1:8080\njava.io.IOException: Connection reset by peer\n at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[na:1.7.0_65]\n at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[na:1.7.0_65]\n at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[na:1.7.0_65]\n at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[na:1.7.0_65]\n at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:379) ~[na:1.7.0_65]\n at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:446) ~[netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:878) ~[netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:225) ~[netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:114) ~[netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:507) [netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:464) [netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:378) [netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:350) [netty-all-4.0.20.Final.jar:4.0.20.Final]\n at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116) [netty-all-4.0.20.Final.jar:4.0.20.Final]\n at java.lang.Thread.run(Thread.java:745) [na:1.7.0_65]\n17:42:57.137 [nioEventLoopGroup-2-1] INFO e.u.t.r.s.c.c.ActivityLoggingHandler - Server /127.0.0.1:8080 closed the connection.\n```\n\nSaludos!\n", "I also observed this XXX and YYY both consume exceptions. My simple fix is just to override exceptionCaught with:\r\n\r\n```\r\n @Override\r\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {\r\n try {\r\n // Allow the pipeline to deal with the exception before the parent.\r\n ctx.fireExceptionCaught(cause);\r\n } finally {\r\n super.exceptionCaught(ctx, cause);\r\n }\r\n }\r\n```\r\n\r\nBefore this fixed, I get a closed channel with no explanation:\r\n```\r\njava.lang.Exception: connection closed\r\n\tat com.civitaslearning.phonehome.server.TunnelServerBootstrapConfiguration$ServerTunnelChannelInitializer.lambda$initChannel$0(TunnelServerBootstrapConfiguration.java:186) ~[main/:?]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:500) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:479) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPromise.trySuccess(DefaultChannelPromise.java:82) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannel$CloseFuture.setClosed(AbstractChannel.java:1058) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannel$AbstractUnsafe.doClose0(AbstractChannel.java:686) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:664) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannel$AbstractUnsafe.close(AbstractChannel.java:607) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline$HeadContext.close(DefaultChannelPipeline.java:1276) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.logging.LoggingHandler.close(LoggingHandler.java:217) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler$8.operationComplete(SslHandler.java:1630) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler$8.operationComplete(SslHandler.java:1619) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.addListener(DefaultPromise.java:163) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:93) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:28) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.safeClose(SslHandler.java:1619) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.closeOutboundAndChannel(SslHandler.java:1430) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.close(SslHandler.java:575) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelOutboundHandlerAdapter.close(ChannelOutboundHandlerAdapter.java:71) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelDuplexHandler.close(ChannelDuplexHandler.java:73) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelOutboundHandlerAdapter.close(ChannelOutboundHandlerAdapter.java:71) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelDuplexHandler.close(ChannelDuplexHandler.java:73) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelDuplexHandler.close(ChannelDuplexHandler.java:73) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelDuplexHandler.close(ChannelDuplexHandler.java:73) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.logging.LoggingHandler.close(LoggingHandler.java:217) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeClose(AbstractChannelHandlerContext.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:608) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:465) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline.close(DefaultChannelPipeline.java:964) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannel.close(AbstractChannel.java:234) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelFutureListener$1.operationComplete(ChannelFutureListener.java:44) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.ChannelFutureListener$1.operationComplete(ChannelFutureListener.java:41) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultPromise.addListener(DefaultPromise.java:163) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:93) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:28) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.protocolViolation(WebSocket08FrameDecoder.java:424) [netty-codec-http-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.protocolViolation(WebSocket08FrameDecoder.java:412) [netty-codec-http-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.decode(WebSocket08FrameDecoder.java:277) [netty-codec-http-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1240) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1041) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.logging.LoggingHandler.channelRead(LoggingHandler.java:233) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:559) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:476) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:438) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]\r\n```\r\n\r\nAfter the fix, I get a clear stack trace showing the error:\r\n```\r\nio.netty.handler.codec.CorruptedFrameException: Max frame length of 65536 has been exceeded.\r\n\tat io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.protocolViolation(WebSocket08FrameDecoder.java:412) ~[netty-codec-http-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.http.websocketx.WebSocket08FrameDecoder.decode(WebSocket08FrameDecoder.java:277) ~[netty-codec-http-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411) ~[netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248) ~[netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1240) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1041) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248) [netty-codec-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.handler.logging.LoggingHandler.channelRead(LoggingHandler.java:233) [netty-handler-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:624) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:559) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:476) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:438) [netty-transport-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) [netty-common-4.1.9.Final.jar:4.1.9.Final]\r\n\tat java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]\r\n```\r\n\r\nI got this because compression was, in some cases _increasing_ the size of the message, and I was creating messages with sizes exactly equal to the max frame size. I'm going to open another bug about that -- it seems that compression should be dropped if it leads to a larger frame.", "I want to improve this -- the silent close bit our project twice, once when it was 100% our own fault caused by a mis-configuration between client and server and a silent close only for large messages and once because of #6663. I see 2 easy and one harder solution, and I am not at all sure which one makes most sense:\r\n\r\n1. (trivial) Add a simple warn (or info?) message when the close happens, particularly when caused by a protocol violation or similar which can be caused by simple misconfiguration.\r\n2. (trivial) Re-fire the exceptionCaught event and then close, with our without try/finally.\r\n3. (harder) Alter implementations of `WebSocketFrameDecoder`to avoid throwing known errors, since they are caught and swallowed in `WebSocketProtocolHandler`/`WebSocketProtocolServerHandler`, anyway. Instead, just log and close there. Note that `WebSocket08FrameDecoder#protocolViolation` closes the channel after the response, anyway.\r\n\r\nPlease advise. If there's a better solution, I'm happing implementing that, too.", "I think 2) would be fine @mkw . Thanks!", "Fixed by https://github.com/netty/netty/pull/6688" ]
[]
"2017-05-01T17:50:01Z"
[ "defect" ]
WebSocketServerProtocolHandler breaks ChannelHandler's exceptionCaught behavior
`WebSocketServerProtocolHandler` overrides `exceptionCaught` method. If an exception happens in the pipeline before `WebSocketServerProtocolHandler` it closes the channel, leaving the Handlers that follow it unable to handle the `Exception`. This is the `WebSocketServerProtocolHandler's` `exceptionCaught` code: ``` java @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof WebSocketHandshakeException) { FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer(cause.getMessage().getBytes())); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { ctx.close(); } } ``` This is my scenario: after an successful handshake, the server has this pipeline: `Pipeline = [wsdecoder, wsencoder, WS403Responder, WebSocketServerProtocolHandler, domainHandler, DefaultChannelPipeline$TailContext#0]` My server logic is in domainHandler. I set `maxFrameSize` in `WebSocketServerProtocolHandler` to be 1MB. If I send a file bigger than this wsdecoder (`WebSocket08FrameDecoder`) calls protocolViolation, which sends an `CloseWebSocketFrame` to the client and throws an `CorruptedFrameException`. This exception is then captured by `WebSocketServerProtocolHandler's` `exceptionCaught` that closes the channel and doesn't call the next handler's `exceptionCaught` (my domain handler) leaving me no chance to change the behavior. This is the `WebSocket08FrameDecoder's` `protocolViolation` code: ``` java private void protocolViolation(ChannelHandlerContext ctx, CorruptedFrameException ex) { state = State.CORRUPT; if (ctx.channel().isActive()) { Object closeMessage; if (receivedClosingHandshake) { closeMessage = Unpooled.EMPTY_BUFFER; } else { closeMessage = new CloseWebSocketFrame(1002, null); } ctx.writeAndFlush(closeMessage).addListener(ChannelFutureListener.CLOSE); } throw ex; } ``` Thanks for this amazing framework, I'm learning a lot thanks to you :-) Saludos.
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java index bb150e39b09..7037ae34686 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java @@ -39,6 +39,7 @@ protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Obje @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.fireExceptionCaught(cause); ctx.close(); } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java index e6e7e38b74e..6b5ef13af53 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java @@ -178,6 +178,7 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer(cause.getMessage().getBytes())); ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { + ctx.fireExceptionCaught(cause); ctx.close(); } }
null
train
train
"2017-04-29T14:10:00"
"2014-10-28T15:10:51Z"
mereshow
val
netty/netty/6698_6699
netty/netty
netty/netty/6698
netty/netty/6699
[ "timestamp(timedelta=39.0, similarity=0.8742627997936318)" ]
464ae9fb7a1710c63646467fd0ca34c78bd1747a
dd8c47741fb5dfb4f4f287576438a58ac68c8ad6
[ "Fixed by #6699" ]
[ "maybe just merge these two lines ?\r\n\r\n`promise.unvoid().addListener(....)`", "use `HttpHeaderValues.CLOSE`", "use `HttpHeaderValues.CLOSE`", "@normanmaurer the next line is \r\n\r\n`super.write(ctx, msg, promise);`\r\n\r\nso I think newly created promise should be passed there. Am I wrong?", "ah yeah... then yes.", "Or you mean this \r\n\r\n`promise = promise.unvoid().addListener(ChannelFutureListener.CLOSE);`\r\n\r\n?" ]
"2017-05-03T21:40:45Z"
[ "defect" ]
HttpServerKeepAliveHandler throws java.lang.IllegalStateException: void future
### Expected behavior No error when I do `ctx.writeAndFlush(msg, ctx.voidPromise());` where msg is with header "Connection:close". ### Actual behavior HttpServerKeepAliveHandler throws IllegalStateException exception. ### Steps to reproduce Use `ctx.writeAndFlush(msg, ctx.voidPromise());` where msg is `DefaultFullHttpResponse` with header "Connection:close". ``` java.lang.IllegalStateException: void future at io.netty.channel.VoidChannelPromise.fail(VoidChannelPromise.java:178) ~[netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.VoidChannelPromise.addListener(VoidChannelPromise.java:44) ~[netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.VoidChannelPromise.addListener(VoidChannelPromise.java:24) ~[netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.handler.codec.http.HttpServerKeepAliveHandler.write(HttpServerKeepAliveHandler.java:85) ~[netty-codec-http-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:816) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.handler.stream.ChunkedWriteHandler.doFlush(ChunkedWriteHandler.java:304) [netty-handler-4.1.10.Final.jar:4.1.10.Final] at io.netty.handler.stream.ChunkedWriteHandler.flush(ChunkedWriteHandler.java:137) [netty-handler-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush(AbstractChannelHandlerContext.java:802) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:814) [netty-transport-4.1.10.Final.jar:4.1.10.Final] at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:794) [netty-transport-4.1.10.Final.jar:4.1.10.Final] ``` ### Netty version 4.1.10
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpServerKeepAliveHandlerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java index c6305a5e2a2..28813332857 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerKeepAliveHandler.java @@ -82,7 +82,7 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) } } if (msg instanceof LastHttpContent && !shouldKeepAlive()) { - promise.addListener(ChannelFutureListener.CLOSE); + promise = promise.unvoid().addListener(ChannelFutureListener.CLOSE); } super.write(ctx, msg, promise); }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerKeepAliveHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerKeepAliveHandlerTest.java index bcd64bebad0..1332a2b8a89 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerKeepAliveHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpServerKeepAliveHandlerTest.java @@ -117,6 +117,34 @@ public void test_KeepAlive() throws Exception { assertFalse(channel.finishAndReleaseAll()); } + @Test + public void testConnectionCloseHeaderHandledCorrectly() throws Exception { + HttpResponse response = new DefaultFullHttpResponse(httpVersion, responseStatus); + response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); + setupMessageLength(response); + + channel.writeAndFlush(response); + HttpResponse writtenResponse = channel.readOutbound(); + + assertFalse(channel.isOpen()); + ReferenceCountUtil.release(writtenResponse); + assertFalse(channel.finishAndReleaseAll()); + } + + @Test + public void testConnectionCloseHeaderHandledCorrectlyForVoidPromise() throws Exception { + HttpResponse response = new DefaultFullHttpResponse(httpVersion, responseStatus); + response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); + setupMessageLength(response); + + channel.writeAndFlush(response, channel.voidPromise()); + HttpResponse writtenResponse = channel.readOutbound(); + + assertFalse(channel.isOpen()); + ReferenceCountUtil.release(writtenResponse); + assertFalse(channel.finishAndReleaseAll()); + } + @Test public void test_PipelineKeepAlive() { FullHttpRequest firstRequest = new DefaultFullHttpRequest(httpVersion, HttpMethod.GET, "/v1/foo/bar");
train
train
"2017-05-03T23:14:39"
"2017-05-03T20:57:22Z"
doom369
val
netty/netty/6709_6713
netty/netty
netty/netty/6709
netty/netty/6713
[ "timestamp(timedelta=28.0, similarity=0.8917066281732946)" ]
0db2901f4db2d3f12b2febe220da113a9e3ed100
015496d5e3cdcde1a7ae8bde281a503eb640f441
[ "@sudheeshkatkam will check... thanks!", "@sudheeshkatkam PTAL https://github.com/netty/netty/pull/6713", "LGTM!", "Fixed by https://github.com/netty/netty/pull/6713" ]
[ "nit: add static import for `SslUtils.getEncryptedPacketLength`", "done..." ]
"2017-05-08T03:56:36Z"
[ "defect" ]
SslHandler does not work with little endian buffers
### Expected behavior SslHandler to work regardless of LE or BE buffers ### Actual behavior SslHandler uses [SslUtils#getEncryptedPacketLength](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/SslUtils.java#L123) which does not work with little endian buffers. Looks like the issue was fixed in [16750ff](https://github.com/netty/netty/commit/16750ffc2802e6098e624df56ea6fbbe5c1055c3) but the change was not carried forward. I suspect there is an alternative then? From the doc in the fix: > Reads a big-endian short integer from the buffer. Please note that we do not use > {@link ChannelBuffer#getShort(int)} because it might be a little-endian buffer. ### Minimal yet complete reproducer code (or URL to code) Code to reproduce the issue is here: [8b415c1](https://github.com/sudheeshkatkam/netty/commit/8b415c1949e0320b4fa1b7a2c7430c1af4eabd52). This bootstraps the chat server and client with a little endian bytebuf allocator, and adds details to console output. To reproduce the failure (handshake timeout), start server using this command (in root directory): > ./run-example.sh -Dlebba=true securechat-server And then the client, using this command: > ./run-example.sh -Dlebba=true securechat-client To fix the use, apply a modified version of [16750ff](https://github.com/netty/netty/commit/16750ffc2802e6098e624df56ea6fbbe5c1055c3) which is here: [f7da006](https://github.com/sudheeshkatkam/netty/commit/f7da006152eaaee40b3482b7126e2f1f2bd90b3d). ### Netty version 4.1 ### JVM version (e.g. `java -version`) java version "1.8.0_77" Java(TM) SE Runtime Environment (build 1.8.0_77-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
[ "handler/src/main/java/io/netty/handler/ssl/SslUtils.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslUtils.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslUtilsTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslUtils.java b/handler/src/main/java/io/netty/handler/ssl/SslUtils.java index dbb22609eea..bdf65672485 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslUtils.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslUtils.java @@ -17,11 +17,13 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.base64.Base64Dialect; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import javax.net.ssl.SSLHandshakeException; /** @@ -120,7 +122,7 @@ static int getEncryptedPacketLength(ByteBuf buffer, int offset) { int majorVersion = buffer.getUnsignedByte(offset + 1); if (majorVersion == 3) { // SSLv3 or TLS - packetLength = buffer.getUnsignedShort(offset + 3) + SSL_RECORD_HEADER_LENGTH; + packetLength = unsignedShortBE(buffer, offset + 3) + SSL_RECORD_HEADER_LENGTH; if (packetLength <= SSL_RECORD_HEADER_LENGTH) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; @@ -137,11 +139,8 @@ static int getEncryptedPacketLength(ByteBuf buffer, int offset) { int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 - if (headerLength == 2) { - packetLength = (buffer.getShort(offset) & 0x7FFF) + 2; - } else { - packetLength = (buffer.getShort(offset) & 0x3FFF) + 3; - } + packetLength = headerLength == 2 ? + (shortBE(buffer, offset) & 0x7FFF) + 2 : (shortBE(buffer, offset) & 0x3FFF) + 3; if (packetLength <= headerLength) { return NOT_ENOUGH_DATA; } @@ -152,12 +151,33 @@ static int getEncryptedPacketLength(ByteBuf buffer, int offset) { return packetLength; } + // Reads a big-endian unsigned short integer from the buffer + @SuppressWarnings("deprecation") + private static int unsignedShortBE(ByteBuf buffer, int offset) { + return buffer.order() == ByteOrder.BIG_ENDIAN ? + buffer.getUnsignedShort(offset) : buffer.getUnsignedShortLE(offset); + } + + // Reads a big-endian short integer from the buffer + @SuppressWarnings("deprecation") + private static short shortBE(ByteBuf buffer, int offset) { + return buffer.order() == ByteOrder.BIG_ENDIAN ? + buffer.getShort(offset) : buffer.getShortLE(offset); + } + private static short unsignedByte(byte b) { return (short) (b & 0xFF); } - private static int unsignedShort(short s) { - return s & 0xFFFF; + // Reads a big-endian unsigned short integer from the buffer + private static int unsignedShortBE(ByteBuffer buffer, int offset) { + return shortBE(buffer, offset) & 0xFFFF; + } + + // Reads a big-endian short integer from the buffer + private static short shortBE(ByteBuffer buffer, int offset) { + return buffer.order() == ByteOrder.BIG_ENDIAN ? + buffer.getShort(offset) : ByteBufUtil.swapShort(buffer.getShort(offset)); } static int getEncryptedPacketLength(ByteBuffer[] buffers, int offset) { @@ -207,7 +227,7 @@ private static int getEncryptedPacketLength(ByteBuffer buffer) { int majorVersion = unsignedByte(buffer.get(pos + 1)); if (majorVersion == 3) { // SSLv3 or TLS - packetLength = unsignedShort(buffer.getShort(pos + 3)) + SSL_RECORD_HEADER_LENGTH; + packetLength = unsignedShortBE(buffer, pos + 3) + SSL_RECORD_HEADER_LENGTH; if (packetLength <= SSL_RECORD_HEADER_LENGTH) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; @@ -224,11 +244,8 @@ private static int getEncryptedPacketLength(ByteBuffer buffer) { int majorVersion = unsignedByte(buffer.get(pos + headerLength + 1)); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 - if (headerLength == 2) { - packetLength = (buffer.getShort(pos) & 0x7FFF) + 2; - } else { - packetLength = (buffer.getShort(pos) & 0x3FFF) + 3; - } + packetLength = headerLength == 2 ? + (shortBE(buffer, pos) & 0x7FFF) + 2 : (shortBE(buffer, pos) & 0x3FFF) + 3; if (packetLength <= headerLength) { return NOT_ENOUGH_DATA; }
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslUtilsTest.java b/handler/src/test/java/io/netty/handler/ssl/SslUtilsTest.java new file mode 100644 index 00000000000..c1de33dd6e3 --- /dev/null +++ b/handler/src/test/java/io/netty/handler/ssl/SslUtilsTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.ssl; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import org.junit.Test; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.NoSuchAlgorithmException; + +import static io.netty.handler.ssl.SslUtils.getEncryptedPacketLength; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class SslUtilsTest { + + @SuppressWarnings("deprecation") + @Test + public void testPacketLength() throws SSLException, NoSuchAlgorithmException { + SSLEngine engineLE = newEngine(); + SSLEngine engineBE = newEngine(); + + ByteBuffer empty = ByteBuffer.allocate(0); + ByteBuffer cTOsLE = ByteBuffer.allocate(17 * 1024).order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer cTOsBE = ByteBuffer.allocate(17 * 1024); + + assertTrue(engineLE.wrap(empty, cTOsLE).bytesProduced() > 0); + cTOsLE.flip(); + + assertTrue(engineBE.wrap(empty, cTOsBE).bytesProduced() > 0); + cTOsBE.flip(); + + ByteBuf bufferLE = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).writeBytes(cTOsLE); + ByteBuf bufferBE = Unpooled.buffer().writeBytes(cTOsBE); + + // Test that the packet-length for BE and LE is the same + assertEquals(getEncryptedPacketLength(bufferBE, 0), getEncryptedPacketLength(bufferLE, 0)); + assertEquals(getEncryptedPacketLength(new ByteBuffer[] { bufferBE.nioBuffer() }, 0), + getEncryptedPacketLength(new ByteBuffer[] { bufferLE.nioBuffer().order(ByteOrder.LITTLE_ENDIAN) }, 0)); + } + + private static SSLEngine newEngine() throws SSLException, NoSuchAlgorithmException { + SSLEngine engine = SSLContext.getDefault().createSSLEngine(); + engine.setUseClientMode(true); + engine.beginHandshake(); + return engine; + } +}
train
train
"2017-05-11T16:00:55"
"2017-05-06T00:52:53Z"
sudheeshkatkam
val
netty/netty/6717_6719
netty/netty
netty/netty/6717
netty/netty/6719
[ "timestamp(timedelta=8.0, similarity=0.989915987786101)" ]
6a8532acd1451f34bf4f7b93bc7967b6b857238e
d33891140c57b678060c3d0bdfe8d4a5dae7c6d0
[ "@rkapsi sounds good (do it as the RFC). You want to do a PR or should I put it on my back burner ?", "Sounds good, inbound PR shortly", "<3" ]
[ "please also call `ch.finishAndReleaseAll();` if `ch != null`" ]
"2017-05-08T18:14:28Z"
[]
The value of the SNI extension is ASCII encoded but Netty uses UTF-8
The value of the SNI extension is ASCII encoded but Netty's SNI code tries to decode the `byte[]` as UTF-8. The was flagged by @fenik17 in this https://github.com/netty/netty/pull/6623#discussion_r111070719 https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java#L188 https://tools.ietf.org/html/rfc6066#page-6 > "HostName" contains the fully qualified DNS hostname of the server, as understood by the client. The hostname is represented as a byte string using ASCII encoding without a trailing dot. This allows the support of internationalized domain names through the use of A-labels defined in [RFC5890]. DNS hostnames are case-insensitive. The algorithm to compare hostnames is described in [RFC5890], Section 2.3.2.4. ### Expected behavior Do as the RFC says? ### Actual behavior Not doing as the RFC says! ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java index e75c0554f13..86e7eb25be8 100644 --- a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java @@ -29,7 +29,6 @@ import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; -import java.net.IDN; import java.net.SocketAddress; import java.util.List; import java.util.Locale; @@ -186,11 +185,10 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t } final String hostname = in.toString(offset, serverNameLength, - CharsetUtil.UTF_8); + CharsetUtil.US_ASCII); try { - select(ctx, IDN.toASCII(hostname, - IDN.ALLOW_UNASSIGNED).toLowerCase(Locale.US)); + select(ctx, hostname.toLowerCase(Locale.US)); } catch (Throwable t) { PlatformDependent.throwException(t); }
diff --git a/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java index d49bdeaeebe..44cfbe9df93 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SniHandlerTest.java @@ -160,38 +160,71 @@ public void testServerNameParsing() throws Exception { SniHandler handler = new SniHandler(mapping); EmbeddedChannel ch = new EmbeddedChannel(handler); - // hex dump of a client hello packet, which contains hostname "CHAT4。LEANCLOUD。CN" - String tlsHandshakeMessageHex1 = "16030100"; - // part 2 - String tlsHandshakeMessageHex = "bd010000b90303a74225676d1814ba57faff3b366" + - "3656ed05ee9dbb2a4dbb1bb1c32d2ea5fc39e0000000100008c0000001700150000164348" + - "415434E380824C45414E434C4F5544E38082434E000b000403000102000a00340032000e0" + - "00d0019000b000c00180009000a0016001700080006000700140015000400050012001300" + - "0100020003000f0010001100230000000d0020001e0601060206030501050205030401040" + - "20403030103020303020102020203000f00010133740000"; - try { - // Push the handshake message. - // Decode should fail because SNI error + // hex dump of a client hello packet, which contains hostname "CHAT4.LEANCLOUD.CN" + String tlsHandshakeMessageHex1 = "16030100"; + // part 2 + String tlsHandshakeMessageHex = "c6010000c20303bb0855d66532c05a0ef784f7c384feeafa68b3" + + "b655ac7288650d5eed4aa3fb52000038c02cc030009fcca9cca8ccaac02b" + + "c02f009ec024c028006bc023c0270067c00ac0140039c009c0130033009d" + + "009c003d003c0035002f00ff010000610000001700150000124348415434" + + "2e4c45414e434c4f55442e434e000b000403000102000a000a0008001d00" + + "170019001800230000000d0020001e060106020603050105020503040104" + + "0204030301030203030201020202030016000000170000"; + ch.writeInbound(Unpooled.wrappedBuffer(DatatypeConverter.parseHexBinary(tlsHandshakeMessageHex1))); ch.writeInbound(Unpooled.wrappedBuffer(DatatypeConverter.parseHexBinary(tlsHandshakeMessageHex))); - fail(); - } catch (DecoderException e) { - // expected + + // This should produce an alert + assertTrue(ch.finish()); + + assertThat(handler.hostname(), is("chat4.leancloud.cn")); + assertThat(handler.sslContext(), is(leanContext)); + } finally { + ch.finishAndReleaseAll(); } + } finally { + releaseAll(leanContext, leanContext2, nettyContext); + } + } - // This should produce an alert - assertTrue(ch.finish()); + @Test(expected = DecoderException.class) + public void testNonAsciiServerNameParsing() throws Exception { + SslContext nettyContext = makeSslContext(provider, false); + SslContext leanContext = makeSslContext(provider, false); + SslContext leanContext2 = makeSslContext(provider, false); - assertThat(handler.hostname(), is("chat4.leancloud.cn")); - assertThat(handler.sslContext(), is(leanContext)); + try { + DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext) + .add("*.netty.io", nettyContext) + // input with custom cases + .add("*.LEANCLOUD.CN", leanContext) + // a hostname conflict with previous one, since we are using order-sensitive config, + // the engine won't be used with the handler. + .add("chat4.leancloud.cn", leanContext2) + .build(); - for (;;) { - Object msg = ch.readOutbound(); - if (msg == null) { - break; - } - ReferenceCountUtil.release(msg); + SniHandler handler = new SniHandler(mapping); + EmbeddedChannel ch = new EmbeddedChannel(handler); + + try { + // hex dump of a client hello packet, which contains an invalid hostname "CHAT4。LEANCLOUD。CN" + String tlsHandshakeMessageHex1 = "16030100"; + // part 2 + String tlsHandshakeMessageHex = "bd010000b90303a74225676d1814ba57faff3b366" + + "3656ed05ee9dbb2a4dbb1bb1c32d2ea5fc39e0000000100008c0000001700150000164348" + + "415434E380824C45414E434C4F5544E38082434E000b000403000102000a00340032000e0" + + "00d0019000b000c00180009000a0016001700080006000700140015000400050012001300" + + "0100020003000f0010001100230000000d0020001e0601060206030501050205030401040" + + "20403030103020303020102020203000f00010133740000"; + + // Push the handshake message. + // Decode should fail because of the badly encoded "HostName" string in the SNI extension + // that isn't ASCII as per RFC 6066 - https://tools.ietf.org/html/rfc6066#page-6 + ch.writeInbound(Unpooled.wrappedBuffer(DatatypeConverter.parseHexBinary(tlsHandshakeMessageHex1))); + ch.writeInbound(Unpooled.wrappedBuffer(DatatypeConverter.parseHexBinary(tlsHandshakeMessageHex))); + } finally { + ch.finishAndReleaseAll(); } } finally { releaseAll(leanContext, leanContext2, nettyContext);
train
train
"2017-05-19T19:36:04"
"2017-05-08T17:57:24Z"
rkapsi
val
netty/netty/6736_6748
netty/netty
netty/netty/6736
netty/netty/6748
[ "timestamp(timedelta=3.0, similarity=0.8843457443954279)" ]
4c6d946fbadfb14806f8232b844c5e6a26eff2de
0a97712c94f5f8cdf6bffcf5af51a7f1f5c15385
[ "@trustin can you submit a pr with a fix ?", "Can't promise it at the moment because of busyness... 😢 ", "> The expected behavior of DnsNameResolver is to try somehost and then somehost.linecorp.local.\r\n\r\nThe behavior of modifying the hostname should be provided at a higher layer (e.g. [DnsNameResolverContext.java](https://github.com/netty/netty/blob/4.1/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java#L141)). However `UnixResolverDnsServerAddressStreamProvider` default value when no match was found needs some work.", "See PR https://github.com/netty/netty/pull/6748" ]
[ "this seems to be not related to the PR. can you revert ?", "Yes this is not directly related to this change but it makes unit testing more difficult. If I pull this out I would also pull the unit tests out (and submit them together) ... is that preferred from your approach?\r\n\r\nhttps://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man5/resolver.5.html\r\n```\r\nIf there are multiple servers,\r\n the resolver library queries them in the order listed. The algorithm used is to try a name server, and\r\n if the query times out, try the next, until out of name servers, then repeat trying all the name\r\n servers until a maximum number of retries are made.\r\n```", "its fine then... Just was not sure why you did this.", "I will update the commit message" ]
"2017-05-18T00:14:27Z"
[ "defect" ]
Incorrect UnixResolverDnsServerAddressStreamProvider
### Minimal yet complete reproducer code (or URL to code) ```java import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import io.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider; public class ResolverTest { @Rule public final TemporaryFolder folder = new TemporaryFolder(); @Test public void test() throws Exception { File f = folder.newFile(); try (OutputStream out = new FileOutputStream(f)) { out.write(("domain linecorp.local\n" + "nameserver 1.2.3.4\n" + "nameserver 5.6.7.8\n").getBytes(StandardCharsets.UTF_8)); } UnixResolverDnsServerAddressStreamProvider p = new UnixResolverDnsServerAddressStreamProvider(f, null); assertNotNull(p.nameServerAddressStream("somehost")); } } ``` ### Expected behavior `UnixResolverDnsServerAddressStreamProvider.nameServerAddressStream()` should not return `null`. The expected behavior of `DnsNameResolver` is to try `somehost.` and then `somehost.linecorp.local.` ### Actual behavior Attempting to resolve a host will trigger a NPE: ``` java.lang.NullPointerException: nameServerAddrs at io.netty.util.internal.ObjectUtil.checkNotNull(ObjectUtil.java:31) at io.netty.resolver.dns.DnsNameResolverContext.<init>(DnsNameResolverContext.java:120) at io.netty.resolver.dns.DnsNameResolver$SingleResolverContext.<init>(DnsNameResolver.java:659) at io.netty.resolver.dns.DnsNameResolver.doResolveUncached(DnsNameResolver.java:653) at io.netty.resolver.dns.DnsNameResolver.doResolve(DnsNameResolver.java:590) at io.netty.resolver.dns.DnsNameResolver.doResolve(DnsNameResolver.java:523) at io.netty.resolver.SimpleNameResolver.resolve(SimpleNameResolver.java:63) at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:100) at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:66) at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:51) at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:57) at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:32) at io.netty.resolver.AbstractAddressResolver.resolve(AbstractAddressResolver.java:108) at io.netty.bootstrap.Bootstrap.doResolveAndConnect0(Bootstrap.java:208) at io.netty.bootstrap.Bootstrap.doResolveAndConnect(Bootstrap.java:170) at io.netty.bootstrap.Bootstrap.connect(Bootstrap.java:145) ``` ### Netty version 4.1.11 ### Workaround Use `DefaultDnsServerAddressStreamProvider.INSTANCE` instead of `DnsServerAddressStreamProviders.platformDefault()`.
[ "resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java" ]
[ "resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java" ]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java b/resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java index d12c63749bc..c22f3ae6c4d 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProvider.java @@ -27,11 +27,13 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static io.netty.resolver.dns.DefaultDnsServerAddressStreamProvider.DNS_PORT; +import static io.netty.util.internal.ObjectUtil.checkNotNull; import static io.netty.util.internal.StringUtil.indexOfNonWhiteSpace; /** @@ -54,7 +56,7 @@ public final class UnixResolverDnsServerAddressStreamProvider implements DnsServ * Attempt to parse {@code /etc/resolv.conf} and files in the {@code /etc/resolver} directory by default. * A failure to parse will return {@link DefaultDnsServerAddressStreamProvider}. */ - public static DnsServerAddressStreamProvider parseSilently() { + static DnsServerAddressStreamProvider parseSilently() { try { UnixResolverDnsServerAddressStreamProvider nameServerCache = new UnixResolverDnsServerAddressStreamProvider("/etc/resolv.conf", "/etc/resolver"); @@ -80,21 +82,25 @@ public static DnsServerAddressStreamProvider parseSilently() { * @throws IOException If an error occurs while parsing the input files. */ public UnixResolverDnsServerAddressStreamProvider(File etcResolvConf, File... etcResolverFiles) throws IOException { - if (etcResolvConf == null && (etcResolverFiles == null || etcResolverFiles.length == 0)) { - throw new IllegalArgumentException("no files to parse"); + if (etcResolverFiles != null && etcResolverFiles.length == 0) { + throw new IllegalArgumentException("etcResolverFiles must either be null or non-empty"); } - if (etcResolverFiles != null) { - domainToNameServerStreamMap = parse(etcResolverFiles); - if (etcResolvConf != null) { - Map<String, DnsServerAddresses> etcResolvConfMap = parse(etcResolvConf); - defaultNameServerAddresses = etcResolvConfMap.remove(etcResolvConf.getName()); - domainToNameServerStreamMap.putAll(etcResolvConfMap); - } else { - defaultNameServerAddresses = null; + Map<String, DnsServerAddresses> etcResolvConfMap = parse(checkNotNull(etcResolvConf, "etcResolvConf")); + domainToNameServerStreamMap = etcResolverFiles != null ? parse(etcResolverFiles) : etcResolvConfMap; + + DnsServerAddresses defaultNameServerAddresses = etcResolvConfMap.get(etcResolvConf.getName()); + if (defaultNameServerAddresses == null) { + Collection<DnsServerAddresses> values = etcResolvConfMap.values(); + if (values.isEmpty()) { + throw new IllegalArgumentException(etcResolvConf + " didn't provide any name servers"); } + this.defaultNameServerAddresses = values.iterator().next(); } else { - domainToNameServerStreamMap = parse(etcResolvConf); - defaultNameServerAddresses = domainToNameServerStreamMap.remove(etcResolvConf.getName()); + this.defaultNameServerAddresses = defaultNameServerAddresses; + } + + if (etcResolverFiles != null) { + domainToNameServerStreamMap.putAll(etcResolvConfMap); } } @@ -113,7 +119,7 @@ public UnixResolverDnsServerAddressStreamProvider(File etcResolvConf, File... et */ public UnixResolverDnsServerAddressStreamProvider(String etcResolvConf, String etcResolverDir) throws IOException { this(etcResolvConf == null ? null : new File(etcResolvConf), - etcResolverDir == null ? null :new File(etcResolverDir).listFiles()); + etcResolverDir == null ? null : new File(etcResolverDir).listFiles()); } @Override @@ -121,7 +127,7 @@ public DnsServerAddressStream nameServerAddressStream(String hostname) { for (;;) { int i = hostname.indexOf('.', 1); if (i < 0 || i == hostname.length() - 1) { - return defaultNameServerAddresses != null ? defaultNameServerAddresses.stream() : null; + return defaultNameServerAddresses.stream(); } DnsServerAddresses addresses = domainToNameServerStreamMap.get(hostname); @@ -133,9 +139,8 @@ public DnsServerAddressStream nameServerAddressStream(String hostname) { } } - boolean mayOverrideNameServers() { - return !domainToNameServerStreamMap.isEmpty() || - defaultNameServerAddresses != null && defaultNameServerAddresses.stream().next() != null; + private boolean mayOverrideNameServers() { + return !domainToNameServerStreamMap.isEmpty() || defaultNameServerAddresses.stream().next() != null; } private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) throws IOException { @@ -176,7 +181,7 @@ private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) t port = Integer.parseInt(maybeIP.substring(i + 1)); maybeIP = maybeIP.substring(0, i); } - addresses.add(new InetSocketAddress(SocketUtils.addressByName(maybeIP), port)); + addresses.add(SocketUtils.socketAddress(maybeIP, port)); } else if (line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i < 0) { @@ -184,7 +189,7 @@ private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) t " in file " + etcResolverFile + " value: " + line); } domainName = line.substring(i); - if (addresses != null && !addresses.isEmpty()) { + if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses); } addresses = new ArrayList<InetSocketAddress>(2); @@ -199,7 +204,7 @@ private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) t logger.info("row type {} not supported. ignoring line: {}", SORTLIST_ROW_LABEL, line); } } - if (addresses != null && !addresses.isEmpty()) { + if (!addresses.isEmpty()) { putIfAbsent(domainToNameServerStreamMap, domainName, addresses); } } finally { @@ -217,7 +222,7 @@ private static void putIfAbsent(Map<String, DnsServerAddresses> domainToNameServ String domainName, List<InetSocketAddress> addresses) { // TODO(scott): sortlist is being ignored. - putIfAbsent(domainToNameServerStreamMap, domainName, DnsServerAddresses.shuffled(addresses)); + putIfAbsent(domainToNameServerStreamMap, domainName, DnsServerAddresses.sequential(addresses)); } private static void putIfAbsent(Map<String, DnsServerAddresses> domainToNameServerStreamMap,
diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java new file mode 100644 index 00000000000..bcb61e78d14 --- /dev/null +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java @@ -0,0 +1,94 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.resolver.dns; + +import io.netty.util.CharsetUtil; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; + +import static org.junit.Assert.assertEquals; + +public class UnixResolverDnsServerAddressStreamProviderTest { + @Rule + public final TemporaryFolder folder = new TemporaryFolder(); + + @Test + public void defaultLookupShouldReturnResultsIfOnlySingleFileSpecified() throws Exception { + File f = buildFile("domain linecorp.local\n" + + "nameserver 127.0.0.2\n" + + "nameserver 127.0.0.3\n"); + UnixResolverDnsServerAddressStreamProvider p = + new UnixResolverDnsServerAddressStreamProvider(f, null); + + DnsServerAddressStream stream = p.nameServerAddressStream("somehost"); + assertHostNameEquals("127.0.0.2", stream.next()); + assertHostNameEquals("127.0.0.3", stream.next()); + } + + @Test + public void defaultReturnedWhenNoBetterMatch() throws Exception { + File f = buildFile("domain linecorp.local\n" + + "nameserver 127.0.0.2\n" + + "nameserver 127.0.0.3\n"); + File f2 = buildFile("domain squarecorp.local\n" + + "nameserver 127.0.0.4\n" + + "nameserver 127.0.0.5\n"); + UnixResolverDnsServerAddressStreamProvider p = + new UnixResolverDnsServerAddressStreamProvider(f, f2); + + DnsServerAddressStream stream = p.nameServerAddressStream("somehost"); + assertHostNameEquals("127.0.0.2", stream.next()); + assertHostNameEquals("127.0.0.3", stream.next()); + } + + @Test + public void moreRefinedSelectionReturnedWhenMatch() throws Exception { + File f = buildFile("domain linecorp.local\n" + + "nameserver 127.0.0.2\n" + + "nameserver 127.0.0.3\n"); + File f2 = buildFile("domain dc1.linecorp.local\n" + + "nameserver 127.0.0.4\n" + + "nameserver 127.0.0.5\n"); + UnixResolverDnsServerAddressStreamProvider p = + new UnixResolverDnsServerAddressStreamProvider(f, f2); + + DnsServerAddressStream stream = p.nameServerAddressStream("myhost.dc1.linecorp.local"); + assertHostNameEquals("127.0.0.4", stream.next()); + assertHostNameEquals("127.0.0.5", stream.next()); + } + + private File buildFile(String contents) throws IOException { + File f = folder.newFile(); + OutputStream out = new FileOutputStream(f); + try { + out.write(contents.getBytes(CharsetUtil.UTF_8)); + } finally { + out.close(); + } + return f; + } + + private static void assertHostNameEquals(String expectedHostname, InetSocketAddress next) { + assertEquals("unexpected hostname: " + next, expectedHostname, next.getHostName()); + } +}
train
train
"2017-05-18T20:26:27"
"2017-05-12T08:36:27Z"
trustin
val
netty/netty/6739_6780
netty/netty
netty/netty/6739
netty/netty/6780
[ "timestamp(timedelta=21.0, similarity=0.8848071776930232)" ]
ca9d1658a00fef7be53abeaf499cb78bdc3a5017
cf983846e0d8b39d8a61c6c6449be313e31cecdf
[ "Oh my.... let me see if we can easily fix this 😂\n\n> Am 12.05.2017 um 15:29 schrieb Roger <notifications@github.com>:\n> \n> I don't know if it's worth pursuing but I came yesterday across a network appliance that seemed to perform malformed HTTP based health checks against our Netty application.\n> \n> The HTTP requests looked like this GET /\\r\\n without the version and HttpVersion line 63 was throwing Exceptions.\n> \n> Turns out it's HTTP/0.9 as per RFC 1945 (see section 3.1)\n> \n> If the protocol version is not specified, the recipient must assume that the message is in the simple HTTP/0.9 format.\n> \n> Expected behavior\n> \n> Actual behavior\n> \n> Steps to reproduce\n> \n> Minimal yet complete reproducer code (or URL to code)\n> \n> Netty version\n> \n> JVM version (e.g. java -version)\n> \n> OS version (e.g. uname -a)\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "You really want to implement HTTP/0.9 from the era of before 1996, when almost no web browser worked correctly?\r\n\r\nFor example, Chrome removed HTTP/0.9 https://developers.google.com/web/updates/2016/09/chrome-54-deprecations#http09_deprecated\r\n\r\n> HTTP/0.9 is the predecessor to HTTP/1.x. It lacks many features of its successors. A particular concern for the modern web is its lack of response headers. Without them, there's no way to verify that an HTTP/0.9 response is really an HTTP/0.9 response. This can cause several problems. Examples include, among other problems:\r\n> - Clients that treat certain error responses as valid HTTP/0.9 responses.\r\n> - Servers that fail to close the request socket causing clients to treat responses as a hanging GET which either stays alive eternally or until a user navigates from a page that made the request.\r\n> - Servers that are unable to indicate to the browser that a request failed, which can cause problems with caching heuristics.\r\n\r\n> The only foolproof way to fix issues with HTTP/0.9 is to remove support altogether. Which is why support for HTTP/0.9 is removed in Chrome 54.\r\n\r\nPlease think twice before opening a can of worms. ", "Maybe augment [HttpVersion line 63](https://github.com/netty/netty/blob/4.1/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java#L63) from throwing `IllegalArgumentException(\"text is empty\")` to `IllegalArgumentException(\"text is empty, possibly HTTP/0.9\")` and call it a day.\r\n\r\nThe confusing thing about this issue was that Netty was sending these `HttpRequestDecoder#createInvalidMessage()` messages down the pipeline with the decoder state's exception message being \"text is empty\". ", "Sounds good... want to do a pr?\n\n> Am 25.05.2017 um 16:01 schrieb Roger <notifications@github.com>:\n> \n> Maybe augment HttpVersion line 63 from throwing IllegalArgumentException(\"text is empty\") to IllegalArgumentException(\"text is empty, possibly HTTP/0.9\") and call it a day.\n> \n> The confusing thing about this issue was that Netty was sending these HttpRequestDecoder#createInvalidMessage() messages down the pipeline with the decoder state's exception message being \"text is empty\".\n> \n> —\n> You are receiving this because you were assigned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "@normanmaurer sure, consider it done. :)", "👌\n\n> Am 25.05.2017 um 17:19 schrieb Roger <notifications@github.com>:\n> \n> @normanmaurer sure, consider it done. :)\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Fixed by https://github.com/netty/netty/pull/6780" ]
[]
"2017-05-25T15:42:04Z"
[ "defect" ]
Handle missing version in HTTP request line (a.k.a HTTP/0.9)
I don't know if it's worth pursuing but I came yesterday across a network appliance that seemed to perform malformed HTTP based health checks against our Netty application. The HTTP requests looked like this `GET /\r\n` without the version and [HttpVersion line 63](https://github.com/netty/netty/blob/4.1/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java#L63) was throwing Exceptions. Turns out it's HTTP/0.9 as per [RFC 1945](https://www.ietf.org/rfc/rfc1945.txt) (see section 3.1) > If the protocol version is not specified, the recipient must assume that the message is in the simple HTTP/0.9 format. ### Expected behavior ### Actual behavior ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java index 806a1b7fdef..352ea848c52 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpVersion.java @@ -60,7 +60,7 @@ public static HttpVersion valueOf(String text) { text = text.trim(); if (text.isEmpty()) { - throw new IllegalArgumentException("text is empty"); + throw new IllegalArgumentException("text is empty (possibly HTTP/0.9)"); } // Try to match without convert to uppercase first as this is what 99% of all clients
null
train
train
"2017-05-25T09:28:28"
"2017-05-12T13:29:14Z"
rkapsi
val
netty/netty/6784_6785
netty/netty
netty/netty/6784
netty/netty/6785
[ "timestamp(timedelta=196.0, similarity=0.9871972148863147)" ]
3c4dfed08ae2ce300f6ac1d0794d42a14c344b79
9297bfb0c0767749082c422e9ae3a05ae978d75c
[ "Can you provide a reproducer / testcase?\n\n> Am 26.05.2017 um 18:18 schrieb NSProgrammer <notifications@github.com>:\n> \n> Expected behavior\n> \n> Brotli content passes through with Content-Encoding being untouched\n> \n> Actual behavior\n> \n> Content-Encoding changed to gzip and already encoded content (in brotli) encoded again with gzip\n> \n> Steps to reproduce\n> \n> Encode response with Brotli\n> Set Content-Encoding to \"br\"\n> Netty version\n> \n> 4.1.11\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Here's a unit test\r\n\r\nhttps://github.com/netty/netty/pull/6785/commits/efebcc327ccb61876fb7e70c1ee7cf3ce65a6525" ]
[]
"2017-05-26T16:20:27Z"
[ "defect" ]
Netty force encodes already encoded responses
### Expected behavior Brotli content passes through with Content-Encoding being untouched ### Actual behavior Content-Encoding changed to gzip and already encoded content (in brotli) encoded again with gzip ### Steps to reproduce 1) Encode response with Brotli 2) Set Content-Encoding to "br" ### Netty version 4.1.11
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java index 11c61293338..fcf22e011ad 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java @@ -101,7 +101,9 @@ public void handlerAdded(ChannelHandlerContext ctx) throws Exception { @Override protected Result beginEncode(HttpResponse headers, String acceptEncoding) throws Exception { String contentEncoding = headers.headers().get(HttpHeaderNames.CONTENT_ENCODING); - if (HttpHeaderValues.IDENTITY.contentEqualsIgnoreCase(contentEncoding)) { + if (contentEncoding != null) { + // Content-Encoding was set, either as something specific or as the IDENTITY encoding + // Therefore, we should NOT encode here return null; }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java index 4946328eba2..94b1aa6cd68 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java @@ -395,6 +395,28 @@ public void testIdentity() throws Exception { assertTrue(ch.finishAndReleaseAll()); } + @Test + public void testCustomEncoding() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor()); + assertTrue(ch.writeInbound(newRequest())); + + FullHttpResponse res = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII)); + int len = res.content().readableBytes(); + res.headers().set(HttpHeaderNames.CONTENT_LENGTH, len); + res.headers().set(HttpHeaderNames.CONTENT_ENCODING, "ascii"); + assertTrue(ch.writeOutbound(res)); + + FullHttpResponse response = (FullHttpResponse) ch.readOutbound(); + assertEquals(String.valueOf(len), response.headers().get(HttpHeaderNames.CONTENT_LENGTH)); + assertEquals("ascii", response.headers().get(HttpHeaderNames.CONTENT_ENCODING)); + assertEquals("Hello, World", response.content().toString(CharsetUtil.US_ASCII)); + response.release(); + + assertTrue(ch.finishAndReleaseAll()); + } + private static FullHttpRequest newRequest() { FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); req.headers().set(HttpHeaderNames.ACCEPT_ENCODING, "gzip");
test
train
"2017-05-26T07:56:34"
"2017-05-26T16:18:49Z"
NSProgrammer
val
netty/netty/6761_6788
netty/netty
netty/netty/6761
netty/netty/6788
[ "timestamp(timedelta=3.0, similarity=0.9662848026936318)" ]
d56a7560ead181f987677c71713b8dc815dab67a
4893bbd01fa28e4fefdd628ce1f6086a96ebbed7
[ "@vietj so you say it is package private and it should be not package-private ? Whats your use-case ?", "my use case is to not send content in a response to HEAD, Vert.x has a special subclass (that you actually created) of `HttpObjectEncoder` that forces the usage of direct buffers, so we cannot use the `HttpServerCodec` that handles it.\r\n\r\nAnother motivation is that we might want to handle the HEAD check with a custom implementation of `HttpMessage` (like a boolean) and not use an a FIFO queue of HttpMessage like in `HttpServerCodec`.", "any news about this ?", "Can you just create a PR for this change ?\n\n\nOn 26. May 2017 at 10:26:16, Julien Viet (notifications@github.com) wrote:\n\nisContentAlwaysEmpty\n", "sure I will", "Fixed by https://github.com/netty/netty/pull/6788" ]
[ "false positive", "`{@code true}`", "I tend to [agree with @jodastephen that `{@code ...}` is overhead for `true`, `false`, and `null`](http://blog.joda.org/2012/11/javadoc-coding-standards.html). 😄", "And I fully acknowledge that this is bike-shedding, sorry so much for that.", "![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Remove this unused method parameter \"msg\". [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=squid%3AS1172)\n" ]
"2017-05-29T12:46:08Z"
[ "improvement" ]
HttpObjectEncoder#isContentAlwaysEmpty cannot be overridden by subclasses
### Expected behavior the `HttpObjectEncoder#isContentAlwaysEmpty()` method is package private, so subclasses can change its behavior. Currently Vert.x has a subclass extending `HttpObjectEncoder `. ### Actual behavior the `HttpObjectEncoder#isContentAlwaysEmpty()` method is package private ### Steps to reproduce n/a ### Minimal yet complete reproducer code (or URL to code) n/a ### Netty version 4.1.8.Final ### JVM version (e.g. `java -version`) n/a ### OS version (e.g. `uname -a`) n/a
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java index 7ef528f365a..878a264ab68 100755 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java @@ -195,7 +195,14 @@ private void encodeChunkedContent(ChannelHandlerContext ctx, Object msg, long co } } - boolean isContentAlwaysEmpty(@SuppressWarnings("unused") H msg) { + /** + * Determine whether a message has a content or not. Some message may have headers indicating + * a content without having an actual content, e.g the response to an HEAD or CONNECT request. + * + * @param msg the message to test + * @return {@code true} to signal the message has no content + */ + protected boolean isContentAlwaysEmpty(@SuppressWarnings("unused") H msg) { return false; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java index 29a11992ad5..a009df1145a 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpServerCodec.java @@ -112,7 +112,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> ou private final class HttpServerResponseEncoder extends HttpResponseEncoder { @Override - boolean isContentAlwaysEmpty(@SuppressWarnings("unused") HttpResponse msg) { + protected boolean isContentAlwaysEmpty(@SuppressWarnings("unused") HttpResponse msg) { return HttpMethod.HEAD.equals(queue.poll()); } }
null
val
train
"2017-05-27T08:26:14"
"2017-05-19T15:22:55Z"
vietj
val
netty/netty/6791_6793
netty/netty
netty/netty/6791
netty/netty/6793
[ "timestamp(timedelta=23859.0, similarity=0.8847535486130266)" ]
742ee764241b7db536b320d1c572d78e069142c3
ae2ac78ed90d57e63d4a83900bad9c766ee74383
[ "@rkapsi will check", "@rkapsi Please check https://github.com/netty/netty/pull/6793" ]
[]
"2017-05-30T19:13:51Z"
[ "defect" ]
io.netty.internal.tcnative.* classes bundled with netty-all JAR
I believe none of the `io.netty.internal.tcnative.*` classes is supposed to be bundled with the netty-all JAR but they are... ```bash $ unzip netty-all-4.1.11.Final.jar | grep tcnative creating: io/netty/internal/tcnative/ inflating: io/netty/internal/tcnative/SSL.class inflating: io/netty/internal/tcnative/Buffer.class inflating: io/netty/internal/tcnative/NativeStaticallyReferencedJniMethods.class inflating: io/netty/internal/tcnative/SSLContext.class inflating: io/netty/internal/tcnative/CertificateRequestedCallback.class inflating: io/netty/internal/tcnative/SniHostNameMatcher.class inflating: io/netty/internal/tcnative/Library.class inflating: io/netty/internal/tcnative/SessionTicketKey.class inflating: io/netty/internal/tcnative/CertificateRequestedCallback$KeyMaterial.class inflating: io/netty/internal/tcnative/CertificateVerifier.class ``` ... causing classpath problems if one is trying to use the netty-all JAR along with a custom TCN build. ### Expected behavior ### Actual behavior ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "all/pom.xml" ]
[ "all/pom.xml" ]
[]
diff --git a/all/pom.xml b/all/pom.xml index 47e763f50de..d7b0b124eb0 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -551,7 +551,7 @@ <goal>unpack-dependencies</goal> </goals> <configuration> - <excludes>io/netty/example/**,META-INF/native/libnetty-tcnative*,META-INF/native/include/**,META-INF/native/**/*.a</excludes> + <excludes>io/netty/internal/tcnative/**,io/netty/example/**,META-INF/native/libnetty-tcnative*,META-INF/native/include/**,META-INF/native/**/*.a</excludes> <includes>io/netty/**,META-INF/native/**</includes> <includeScope>runtime</includeScope> <includeGroupIds>${project.groupId}</includeGroupIds>
null
train
train
"2017-05-30T17:53:36"
"2017-05-30T17:23:14Z"
rkapsi
val
netty/netty/6802_6807
netty/netty
netty/netty/6802
netty/netty/6807
[ "timestamp(timedelta=0.0, similarity=0.9428825409266821)" ]
24f801c7d1d1e66193d6ff0da3b93ce427b2b329
f8788a9f6cbad154c505c63be9602f2eb324e0c8
[ "@mousom - ping (for reference see [1])\r\n\r\n@Sammers21 - You can see how PUBLISH is encoded here [2]. Do you think there is an issue with this?\r\n\r\n[1] http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html#_Toc385349775\r\n[2] https://github.com/netty/netty/blob/4.1/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java#L298", "@Scottmitch, After reading how PUBLISH packet encodes I would assume that messageId in code is the same thing as Packet Identifier in spec. Maybe it would be better to rename messageId field into packetId? \r\nCan I create PR?", "@Sammers21 I think we can not rename interface methods as we otherwise would break user-code or you talking about something else ?", "@normanmaurer, yes, you are right, renaming of one of the fields would break user code. But in my point of view, fields should are named in the same way as it in a protocol otherwise it can be tricky for new users to understand what the field really mean.", "If you want to submit a PR to correct naming you can deprecate the existing accessors and refer to the new accessors (if you think its worth it).", "@Scottmitch , I have marked the old method with @deprecated and opened PR. Check it out." ]
[]
"2017-06-02T17:20:15Z"
[]
Not specified field in MQTT codec
### Expected behavior According to the [MQTT 3.1.1 spec](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html), the variable header must not have a messageId in the variable header when publishing PUBLISH packet. It must have only these two: Topic Name and Packet Identifier. ### Actual behavior In io.netty.handler.codec.mqtt.MqttPublishVariableHeader there are two fields and one of them is messageId which is not specified. ### Question What the meaning of messageId field in MqttPublishVariableHeader? Thank you, Pavel
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java" ]
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java" ]
[]
diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java index 6422d53b901..a0d0481b14c 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttPublishVariableHeader.java @@ -24,19 +24,27 @@ public final class MqttPublishVariableHeader { private final String topicName; - private final int messageId; + private final int packetId; - public MqttPublishVariableHeader(String topicName, int messageId) { + public MqttPublishVariableHeader(String topicName, int packetId) { this.topicName = topicName; - this.messageId = messageId; + this.packetId = packetId; } public String topicName() { return topicName; } + /** + * @deprecated Use {@link #packetId()} instead. + */ + @Deprecated public int messageId() { - return messageId; + return packetId; + } + + public int packetId() { + return packetId; } @Override @@ -44,7 +52,7 @@ public String toString() { return new StringBuilder(StringUtil.simpleClassName(this)) .append('[') .append("topicName=").append(topicName) - .append(", messageId=").append(messageId) + .append(", packetId=").append(packetId) .append(']') .toString(); }
null
train
train
"2017-06-02T16:47:35"
"2017-06-01T22:32:51Z"
Sammers21
val
netty/netty/6808_6809
netty/netty
netty/netty/6808
netty/netty/6809
[ "timestamp(timedelta=25.0, similarity=0.8503605160022504)" ]
f8788a9f6cbad154c505c63be9602f2eb324e0c8
13509878a805401d24f45df90aa7b5702eb4c5c6
[ "This appears to be a very deliberate behavior, but I don't see a reason other than for implementation convenience. I'm happy to take a look at this if you're willing to accept a patch.", "IIUC it was done out of convenience (not required ... chunked should be \"semantically correct\" in either case so no need for a specialization). However a PR to adjust `content-length` if full object sgtm.", "@Scottmitch thanks for the quick reply. I've opened a PR, #6809, that preserves the `content-length` header for full responses.", "fixed by https://github.com/netty/netty/pull/6809" ]
[ "in runtime an `assert` block is ignoring if `-ea` option has not specified.", "We don't want this to be an `assert`, right? `assert` statements can be disabled via command line and optimized away by JIT.", "consider just directly casting to the object you expect like the other tests ... a class cast exception will be thrown if the expected type is not read.", "Removed.", "Done." ]
"2017-06-02T21:04:37Z"
[ "improvement" ]
HttpContentCompressor/HttpContentEncoder should reset the content-length header for FullHttpMessages
### Expected behavior When the `HttpContentEncoder` is tasked with compressing a full `HttpMessage` that already contains a `Content-Length` header it should perform the compression and _adjust_ the `Content-Length`. ### Actual behavior All messages compressed result in `Transfer-Encoding: Chunked` and don't have a `Content-Length` header. ### Minimal yet complete reproducer code (or URL to code) ```java @Test public void testAmendContentLength() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor()); ch.writeInbound(newRequest()); ByteBuf content = Unpooled.copiedBuffer("Hello, world!", CharsetUtil.UTF_8); HttpMessage res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); HttpUtil.setContentLength(res, content.readableBytes()); ch.writeOneOutbound(res); HttpMessage compressedResponse = ch.readOutbound(); assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("gzip")); assertTrue(HttpUtil.isContentLengthSet(compressedResponse)); } ``` ### Netty version 4.1 branch at SHA 24f801c7d1d1 (should affect most versions)
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java", "codec-http/src/test/java/io/netty/handler/codec/http/HttpContentEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java index 578deb25999..c04d5386819 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentEncoder.java @@ -164,18 +164,21 @@ protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou // so that the message looks like a decoded message. res.headers().set(HttpHeaderNames.CONTENT_ENCODING, result.targetContentEncoding()); - // Make the response chunked to simplify content transformation. - res.headers().remove(HttpHeaderNames.CONTENT_LENGTH); - res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); - // Output the rewritten response. if (isFull) { // Convert full message into unfull one. HttpResponse newRes = new DefaultHttpResponse(res.protocolVersion(), res.status()); newRes.headers().set(res.headers()); out.add(newRes); - // Fall through to encode the content of the full response. + + ensureContent(res); + encodeFullResponse(newRes, (HttpContent) res, out); + break; } else { + // Make the response chunked to simplify content transformation. + res.headers().remove(HttpHeaderNames.CONTENT_LENGTH); + res.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); + out.add(res); state = State.AWAIT_CONTENT; if (!(msg instanceof HttpContent)) { @@ -205,6 +208,25 @@ protected void encode(ChannelHandlerContext ctx, HttpObject msg, List<Object> ou } } + private void encodeFullResponse(HttpResponse newRes, HttpContent content, List<Object> out) { + int existingMessages = out.size(); + encodeContent(content, out); + + if (HttpUtil.isContentLengthSet(newRes)) { + // adjust the content-length header + int messageSize = 0; + for (int i = existingMessages; i < out.size(); i++) { + Object item = out.get(i); + if (item instanceof HttpContent) { + messageSize += ((HttpContent) item).content().readableBytes(); + } + } + HttpUtil.setContentLength(newRes, messageSize); + } else { + newRes.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); + } + } + private static boolean isPassthru(HttpVersion version, int code, CharSequence httpMethod) { return code < 200 || code == 204 || code == 304 || (httpMethod == ZERO_LENGTH_HEAD || (httpMethod == ZERO_LENGTH_CONNECT && code == 200)) ||
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java index 94b1aa6cd68..c6ff3bd6bc0 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java @@ -198,14 +198,51 @@ public void testChunkedContentWithTrailingHeader() throws Exception { } @Test - public void testFullContent() throws Exception { + public void testFullContentWithContentLength() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor()); ch.writeInbound(newRequest()); - FullHttpResponse res = new DefaultFullHttpResponse( + FullHttpResponse fullRes = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII)); - res.headers().set(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes()); + fullRes.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullRes.content().readableBytes()); + ch.writeOutbound(fullRes); + + HttpResponse res = ch.readOutbound(); + assertThat(res, is(not(instanceOf(HttpContent.class)))); + + assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue())); + assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("gzip")); + + long contentLengthHeaderValue = HttpUtil.getContentLength(res); + long observedLength = 0; + + HttpContent c = ch.readOutbound(); + observedLength += c.content().readableBytes(); + assertThat(ByteBufUtil.hexDump(c.content()), is("1f8b0800000000000000f248cdc9c9d75108cf2fca4901000000ffff")); + c.release(); + + c = ch.readOutbound(); + observedLength += c.content().readableBytes(); + assertThat(ByteBufUtil.hexDump(c.content()), is("0300c6865b260c000000")); + c.release(); + + LastHttpContent last = ch.readOutbound(); + assertThat(last.content().readableBytes(), is(0)); + last.release(); + + assertThat(ch.readOutbound(), is(nullValue())); + assertEquals(contentLengthHeaderValue, observedLength); + } + + @Test + public void testFullContent() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor()); + ch.writeInbound(newRequest()); + + FullHttpResponse res = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.copiedBuffer("Hello, World", CharsetUtil.US_ASCII)); ch.writeOutbound(res); assertEncodedResponse(ch); diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentEncoderTest.java index 660df3406e5..d4bb1af78ba 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentEncoderTest.java @@ -160,14 +160,41 @@ public void testChunkedContentWithTrailingHeader() throws Exception { assertThat(ch.readOutbound(), is(nullValue())); } + @Test + public void testFullContentWithContentLength() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new TestEncoder()); + ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")); + + FullHttpResponse fullRes = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42])); + fullRes.headers().set(HttpHeaderNames.CONTENT_LENGTH, 42); + ch.writeOutbound(fullRes); + + HttpResponse res = ch.readOutbound(); + assertThat(res, is(not(instanceOf(HttpContent.class)))); + assertThat(res.headers().get(HttpHeaderNames.TRANSFER_ENCODING), is(nullValue())); + assertThat(res.headers().get(HttpHeaderNames.CONTENT_LENGTH), is("2")); + assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("test")); + + HttpContent c = ch.readOutbound(); + assertThat(c.content().readableBytes(), is(2)); + assertThat(c.content().toString(CharsetUtil.US_ASCII), is("42")); + c.release(); + + LastHttpContent last = ch.readOutbound(); + assertThat(last.content().readableBytes(), is(0)); + last.release(); + + assertThat(ch.readOutbound(), is(nullValue())); + } + @Test public void testFullContent() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new TestEncoder()); ch.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/")); FullHttpResponse res = new DefaultFullHttpResponse( - HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42])); - res.headers().set(HttpHeaderNames.CONTENT_LENGTH, 42); + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(new byte[42])); ch.writeOutbound(res); assertEncodedResponse(ch);
train
train
"2017-06-05T22:21:49"
"2017-06-02T19:21:36Z"
bryce-anderson
val
netty/netty/6797_6811
netty/netty
netty/netty/6797
netty/netty/6811
[ "timestamp(timedelta=263.0, similarity=0.8796850436353353)" ]
b03b0f22d1e54733c2d39c7f913f971dab14ebfa
ab207aeadba40de1a92ac933b6100b71fe5335e8
[]
[ "nit: `length % 2 != 0` -> `(length & 1) != 0`. you can avoid modulo for a cheaper bit mask operation.", "please change the indexing to the way it was previously. You are adding additional arithmetic on each loop iteration which can be avoided.", "can you include a microbenchmark comparing this method vs `Character.digit(x, 16)`? If `decodeHexNibble` is sufficiently faster we may want to continue to use it.", "In my tests, a `QueryStringDecoder.decodeHexNibble()` faster than `Character.digit()` by ~30%.\r\nAlso `Character.digit()` supports some exotic cases:\r\n```java\r\nCharacter.digit('\\uFF21', 16) => 10 // 'A'\r\nvs normal\r\nCharacter.digit('\\u0041', 16) => 10 // 'A'\r\n```\r\nNot sure that this is correctly for hex-encoding.", "It's too wasteful to allocate new byte array on each encoded byte...", "this will incur an intermediate `byte[]` array and copy operation. We should consider creating a variant of `decodeHexDump` which can directly write into a `ByteBuf` ... something like:\r\n\r\n```java\r\npublic static void decodHexDump(CharSequence hexDump, int start, int len, ByteBuf result) {\r\n...\r\n}\r\n```", "+1 ... I have the same comment below.", "+1 ... I have the same comment below.", "> directly write into a ByteBuf\r\n\r\nOr maybe just a function to deconing one byte?", "I guess either would work in this cause however writing into a `ByteBuf` may be useful if users want to avoid the `byte[]` translation all together ... and this way users don't *have* to know how to properly iterate `hexDump` and the required characteristics.", "@fenik17 Yes, the docs explicitly states so. QueryStringDecoder.decodeHexNibble() is simple and fits our purposes better, I think.", "@Scottmitch\r\nTest result given by @fenik17 above shows that \"QueryStringDecoder.decodeHexNibble() faster than Character.digit() by ~30%.\" This agrees with the fact that Character.digit() tries to address a larger set of letters (ASCII latin+full-width latin; not exactly what we'd expect in escaped URL strings anyway) with a much more complex algorithm, etc.\r\n\r\nSo, let's, say, continue to use decodeHexNibble and drop this PR?", "@Scottmitch For the original code, if I call decodeHexDump() with fromIndex=1024, length=2, \"bytes[fromIndex >>> 1] = ... \"will be referencing bytes[512] while the bytes array is of length 1. That's why I re-wrote this.", "Ok, it makes sense. Just one moment: here `ByteBuffer`, not `ByteBuf`.", "> and drop this PR?\r\n\r\nNo.. Just use `decodeHexNibble()` instead of `Character.digit(x, 16)`.", "makes sense ... that was a bug ... previously we were only decoding from 0 so this went unnoticed.", "@fenik17 - Are you suggesting adding a utility method for `ByteBuffer` instead of `ByteBuf`?", "Move `decodeHexNibble` into `ByteBufUtil` and make it `private static` and use it instead of `Character.digit`", "@Scottmitch I just pointing that in `QueryStringDecoder.decodeComponent()` used a `ByteBuffer`. If we want to use there the method you proposed, will have to make a variant with `ByteBuffer`.", "Oh I see what you are saying now ... makes sense. Not ideal to add a `ByteBuffer` method in `ByteBufUtil` ... maybe we should change `QueryStringDecoder` to use a `ByteBuf` (so we can take advantage of our allocators) and then use `ByteBuf#nioBuffer()` to do the decoding.", "Use `ByteBuf#nioBuffer()` will be too expensive. It smells of overengineering )\r\nIn `QueryStringDecoder.decodeComponent()` needed only decode two characters to one byte...", "> Use ByteBuf#nioBuffer() will be too expensive. It smells of overengineering )\r\n\r\nPerhaps ... if it is too much I'm not against directly adding a `ByteBuffer` utility method.", "I agree with @fenik17 lets keep it simple... " ]
"2017-06-03T01:12:37Z"
[]
QueryStringDecoder and ByteBufUtil decoding hex string duplication
QueryStringDecoder has methods which deal with decoding hex into bytes (e.g. `decodeHexByte`, `decodeHexNibble`) and `ByteBufUtil` has `decodeHexDump`. Can we share code between these two classes?
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java" ]
[ "buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java", "codec-http/src/test/java/io/netty/handler/codec/http/QueryStringDecoderTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index 2dda96bac28..98574503233 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -125,6 +125,13 @@ public static String hexDump(byte[] array, int fromIndex, int length) { return HexUtil.hexDump(array, fromIndex, length); } + /** + * Decode a 2-digit hex byte from within a string. + */ + public static byte decodeHexByte(CharSequence s, int pos) { + return HexUtil.decodeHexByte(s, pos); + } + /** * Decodes a string generated by {@link #hexDump(byte[])} */ @@ -132,6 +139,13 @@ public static byte[] decodeHexDump(CharSequence hexDump) { return HexUtil.decodeHexDump(hexDump, 0, hexDump.length()); } + /** + * Decodes part of a string generated by {@link #hexDump(byte[])} + */ + public static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) { + return HexUtil.decodeHexDump(hexDump, fromIndex, length); + } + /** * Calculates the hash code of the specified buffer. This method is * useful when implementing a new buffer type. @@ -877,20 +891,50 @@ private static String hexDump(ByteBuf buffer, int fromIndex, int length) { return new String(buf); } + /** + * Helper to decode half of a hexadecimal number from a string. + * @param c The ASCII character of the hexadecimal number to decode. + * Must be in the range {@code [0-9a-fA-F]}. + * @return The hexadecimal value represented in the ASCII character + * given, or {@code -1} if the character is invalid. + */ + private static int decodeHexNibble(final char c) { + // Character.digit() is not used here, as it addresses a larger + // set of characters (both ASCII and full-width latin letters). + if ('0' <= c && c <= '9') { + return c - '0'; + } + if ('a' <= c && c <= 'f') { + return c - 'a' + 0xA; + } + if ('A' <= c && c <= 'F') { + return c - 'A' + 0xA; + } + return -1; + } + + private static byte decodeHexByte(CharSequence s, int pos) { + int hi = decodeHexNibble(s.charAt(pos)); + int lo = decodeHexNibble(s.charAt(pos + 1)); + if (hi == -1 || lo == -1) { + throw new IllegalArgumentException(String.format( + "invalid hex byte '%s' at index %d of '%s'", s.subSequence(pos, pos + 2), pos, s)); + } + return (byte) ((hi << 4) + lo); + } + private static byte[] decodeHexDump(CharSequence hexDump, int fromIndex, int length) { - if (length < 0) { + if (length < 0 || (length & 1) != 0) { throw new IllegalArgumentException("length: " + length); } if (length == 0) { return EmptyArrays.EMPTY_BYTES; } - int endIndex = fromIndex + length - 1; byte[] bytes = new byte[length >>> 1]; - for (; fromIndex < endIndex; fromIndex += 2) { - bytes[fromIndex >>> 1] = (byte) ((Character.digit(hexDump.charAt(fromIndex), 16) << 4) + - Character.digit(hexDump.charAt(fromIndex + 1), 16)); + for (int i = 0; i < length; i += 2) { + bytes[i >>> 1] = decodeHexByte(hexDump, fromIndex + i); } return bytes; diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java index 815d779f4fc..3df61e2ca48 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/QueryStringDecoder.java @@ -33,6 +33,7 @@ import static io.netty.util.internal.ObjectUtil.*; import static io.netty.util.internal.StringUtil.*; +import static io.netty.buffer.ByteBufUtil.decodeHexByte; /** * Splits an HTTP query string into a path string and key-value parameter pairs. @@ -330,7 +331,10 @@ private static String decodeComponent(String s, int from, int toExcluded, Charse byteBuf.clear(); do { - byteBuf.put(decodeHexByte(s, i, toExcluded)); + if (i + 3 > toExcluded) { + throw new IllegalArgumentException("unterminated escape sequence at index " + i + " of: " + s); + } + byteBuf.put(decodeHexByte(s, i + 1)); i += 3; } while (i < toExcluded && s.charAt(i) == '%'); i--; @@ -354,39 +358,6 @@ private static String decodeComponent(String s, int from, int toExcluded, Charse return strBuf.toString(); } - private static byte decodeHexByte(String s, int pos, int len) { - if (pos + 2 >= len) { - throw new IllegalArgumentException("unterminated escape sequence at index " + pos + " of: " + s); - } - int hi = decodeHexNibble(s.charAt(pos + 1)); - int lo = decodeHexNibble(s.charAt(pos + 2)); - if (hi == -1 || lo == -1) { - throw new IllegalArgumentException( - "invalid escape sequence '" + s.substring(pos, pos + 3) + "' at index " + pos + " of: " + s); - } - return (byte) ((hi << 4) + lo); - } - - /** - * Helper to decode half of a hexadecimal number from a string. - * @param c The ASCII character of the hexadecimal number to decode. - * Must be in the range {@code [0-9a-fA-F]}. - * @return The hexadecimal value represented in the ASCII character - * given, or {@code -1} if the character is invalid. - */ - private static int decodeHexNibble(final char c) { - if ('0' <= c && c <= '9') { - return c - '0'; - } - if ('a' <= c && c <= 'f') { - return c - 'a' + 0xA; - } - if ('A' <= c && c <= 'F') { - return c - 'A' + 0xA; - } - return -1; - } - private static int findPathEndIndex(String uri) { int len = uri.length(); for (int i = 0; i < len; i++) {
diff --git a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java index e1bf859b2ca..9865ed0109f 100644 --- a/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java +++ b/buffer/src/test/java/io/netty/buffer/ByteBufUtilTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.Random; import static io.netty.buffer.Unpooled.unreleasableBuffer; @@ -31,22 +32,35 @@ public class ByteBufUtilTest { @Test - public void decodeHexEvenLength() { - decodeHex(256); + public void decodeRandomHexBytesWithEvenLength() { + decodeRandomHexBytes(256); } @Test - public void decodeHexOddLength() { - decodeHex(257); + public void decodeRandomHexBytesWithOddLength() { + decodeRandomHexBytes(257); } - private static void decodeHex(int len) { + private static void decodeRandomHexBytes(int len) { byte[] b = new byte[len]; Random rand = new Random(); rand.nextBytes(b); String hexDump = ByteBufUtil.hexDump(b); - byte[] decodedBytes = ByteBufUtil.decodeHexDump(hexDump); - assertArrayEquals(b, decodedBytes); + for (int i = 0; i <= len; i++) { // going over sub-strings of various lengths including empty byte[]. + byte[] b2 = Arrays.copyOfRange(b, i, b.length); + byte[] decodedBytes = ByteBufUtil.decodeHexDump(hexDump, i * 2, (len - i) * 2); + assertArrayEquals(b2, decodedBytes); + } + } + + @Test(expected = IllegalArgumentException.class) + public void decodeHexDumpWithOddLength() { + ByteBufUtil.decodeHexDump("abc"); + } + + @Test(expected = IllegalArgumentException.class) + public void decodeHexDumpWithInvalidChar() { + ByteBufUtil.decodeHexDump("fg"); } @Test diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/QueryStringDecoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/QueryStringDecoderTest.java index 68eb4b808c0..d0d5c1ce90e 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/QueryStringDecoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/QueryStringDecoderTest.java @@ -205,8 +205,8 @@ public void testUrlDecoding() throws Exception { "%42", "B", "%5f", "_", "f%4", "unterminated escape sequence at index 1 of: f%4", - "%x2", "invalid escape sequence '%x2' at index 0 of: %x2", - "%4x", "invalid escape sequence '%4x' at index 0 of: %4x", + "%x2", "invalid hex byte 'x2' at index 1 of '%x2'", + "%4x", "invalid hex byte '4x' at index 1 of '%4x'", "Caff%C3%A9", caffe, "случайный праздник", "случайный праздник", "случайный%20праздник", "случайный праздник",
test
train
"2017-06-07T04:30:04"
"2017-05-31T20:51:59Z"
Scottmitch
val
netty/netty/6804_6816
netty/netty
netty/netty/6804
netty/netty/6816
[ "timestamp(timedelta=43.0, similarity=0.8710672718801298)" ]
f8788a9f6cbad154c505c63be9602f2eb324e0c8
251f77aa9f201ed0704f0ed311deaf61454a6e43
[ "@lsqlebai can you please provide a full reproducer ? Also please update to latest netty version just to be sure.", "sorry the netty version is 4.1.6.Final", "@normanmaurer What would you want? my project is so large. maybe i can give u a demo when i free.", "@lsqlebai I want you to upgrade to latest 4.1. version and try again if it happens. If it still happens provide me some way to reproduce.", "> my project is so large. maybe i can give u a demo when i free.\r\n\r\nIdeally folks that file issues will provide a minimal/complete (so we can run it, but don't have to understand your entire application logic) ... the easier it is to reproduce the more likely we will be able to figure out the issue (assuming its a Netty issue) and fix it.", "@Scottmitch @normanmaurer i wrote a demo, how can i give you? by email or???", "@Scottmitch @normanmaurer would u please try this code: https://github.com/lsqlebai/testzlib\r\nthat can be reproduce .", "I took a brief look. It seems like the issue is in this case the `JdkZlibDecoder` happens to break the decode up into 2 buffers and the `JZlibDecoder` decodes into a single buffer, and the `ProtobufDecoder#decoder` assumes all content is in the same `ByteBuf`. See https://github.com/netty/netty/pull/6816 for a PR which makes the two decoders consistent." ]
[]
"2017-06-05T22:42:07Z"
[ "defect" ]
JDKZlibEncoder or JDKZlibDecoder can't work correct with large data
### Expected behavior work ### Actual behavior decode error(protobuf decode error) ### Steps to reproduce i have 2 server. and them communicate with tcp. and the pipeline init code double with them. when the send data > 16000 byte (maybe less). the decode side can't correct decode (protobuf decode error). ### Minimal yet complete reproducer code (or URL to code) decode error code: Code: ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.NONE)); pipeline.addLast(new ProtobufDecoder(GameServer.ServerData.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE)); pipeline.addLast(new ProtobufEncoder()); i had 2 test: remove zlib, can be work.like this: ChannelPipeline pipeline = ch.pipeline(); //receive pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(GameServer.ServerData.getDefaultInstance())); //send pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); change to the JZlibDecoder and JZlibEncoder can be work. like this: ChannelPipeline pipeline = ch.pipeline(); //receive pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new JZlibDecoder(ZlibWrapper.NONE)); pipeline.addLast(new ProtobufDecoder(GameServer.ServerData.getDefaultInstance())); //send pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new JZlibEncoder(ZlibWrapper.NONE)); pipeline.addLast(new ProtobufEncoder()); ### Netty version 4.1.7 ### JVM version (e.g. `java -version`) java version "1.8.0_101" ### OS version (e.g. `uname -a`) windows
[ "codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java", "codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java", "codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java index ad2ae299044..5d23bb8bd6f 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/JZlibDecoder.java @@ -107,16 +107,15 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t z.next_in = array; z.next_in_index = 0; } - int oldNextInIndex = z.next_in_index; + final int oldNextInIndex = z.next_in_index; // Configure output. - int maxOutputLength = inputLength << 1; - ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength); + ByteBuf decompressed = ctx.alloc().heapBuffer(inputLength << 1); try { loop: for (;;) { - z.avail_out = maxOutputLength; - decompressed.ensureWritable(maxOutputLength); + decompressed.ensureWritable(z.avail_in << 1); + z.avail_out = decompressed.writableBytes(); z.next_out = decompressed.array(); z.next_out_index = decompressed.arrayOffset() + decompressed.writerIndex(); int oldNextOutIndex = z.next_out_index; diff --git a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java index 3594685a242..d9b4b914f19 100644 --- a/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/compression/JdkZlibDecoder.java @@ -167,25 +167,14 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t inflater.setInput(array); } - int maxOutputLength = inflater.getRemaining() << 1; - ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength); + ByteBuf decompressed = ctx.alloc().heapBuffer(inflater.getRemaining() << 1); try { boolean readFooter = false; - byte[] outArray = decompressed.array(); while (!inflater.needsInput()) { + byte[] outArray = decompressed.array(); int writerIndex = decompressed.writerIndex(); int outIndex = decompressed.arrayOffset() + writerIndex; - int length = decompressed.writableBytes(); - - if (length == 0) { - // completely filled the buffer allocate a new one and start to fill it - out.add(decompressed); - decompressed = ctx.alloc().heapBuffer(maxOutputLength); - outArray = decompressed.array(); - continue; - } - - int outputLength = inflater.inflate(outArray, outIndex, length); + int outputLength = inflater.inflate(outArray, outIndex, decompressed.writableBytes()); if (outputLength > 0) { decompressed.writerIndex(writerIndex + outputLength); if (crc != null) { @@ -208,6 +197,8 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t readFooter = true; } break; + } else { + decompressed.ensureWritable(inflater.getRemaining() << 1); } }
null
train
train
"2017-06-05T22:21:49"
"2017-06-02T08:40:40Z"
lsqlebai
val
netty/netty/6750_6817
netty/netty
netty/netty/6750
netty/netty/6817
[ "timestamp(timedelta=0.0, similarity=0.9233935247334096)" ]
b6c27b9f6befa7a66bf23f9a2aa0c9c943981c6a
97d48c65f80d8d90d4bc1962c6c63771d5e4c05a
[ "are you interested in submitting a PR to correct this issue?", "Fixed by https://github.com/netty/netty/pull/681" ]
[ "Please use the same approach (add a new method) as in https://github.com/netty/netty/pull/6769 and avoid breaking the public API.", "can we remove `minBytes` and `maxBytes` parameters? `maxBytes` is always `MAX_VALUE` and `minBytes` is always `0`. can we instead just throw an exception (or return early) if `size < 0`?", "should we deprecate this constructor in favor of the new constructor which takes `byte[]`?", "Please deprecate this method and refer to the `willMessageInBytes` in the `@deprecated` javadocs.", "Please deprecate this method and refer to the `passwordInBytes ` in the `@deprecated` javadocs.", "this is invalid and will throw an exception.", "do you really want to decrement `numberOfBytesConsumed`?", "can you add a unit test which hits this code?", "deprecate this method and reference the new method in javadocs?", "deprecate this method and reference the new method in javadocs?", "This part of the code will be hit only in a hypothetical situation when the encoded bytebuf have some issues like length of a message field, say password is set to -1 etc.\r\n\r\nHowever, if the assumption is, the encoded bytebuf is created out of the MqttEncoder, then this part of the code can be safely commented out.", "I still don't understand this line of code. 2 bytes have still been consumed either way even if the data is invalid. This value is ultimately set to `bytesRemainingInVariablePart` which may be used later during the decode process. You mentioned this was a [hypothetical situation](https://github.com/netty/netty/pull/6817#discussion_r120771580) but it is not clear what will happen if this situation does occur (if its possible at all). If this situation is possible please add a unit test, and if it isn't possible can we remove this line?", "Now a variable `numberOfBytesConsumed` is not needed.\r\n```java\r\nreturn new Result<byte[]>(bytes, decodedSize.numberOfBytesConsumed + size);\r\n```" ]
"2017-06-06T00:53:23Z"
[]
codec.mqtt: wrong password and willMessage field types in MqttConnectPayload/MqttEncoder (should be byte[])
In the present implementation of MqttConnectPayload/MqttEncoder, willMessage and password fields are strings. However, spec (3.1.3.5) clearly mandates that the password filed should support arbitrary binary data: > The Password field contains 0 to 65535 bytes of binary data prefixed with a two byte length field which indicates the number of bytes used by the binary data (it does not include the two bytes taken up by the length field itself). Same for willMessage (3.1.3.3): > This field consists of a two byte length followed by the payload for the Will Message expressed as a sequence of zero or more bytes. Thus, the relevant field and encoder bits must treat the password and willMessage fields as byte[] or ByteBuf (the former is probably enough). This has important practical implications and the fix is straightforward and simple.
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java" ]
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java", "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java" ]
[ "codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java" ]
diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java index 1e16acf4430..e274e3f29e6 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttConnectPayload.java @@ -16,6 +16,7 @@ package io.netty.handler.codec.mqtt; +import io.netty.util.CharsetUtil; import io.netty.util.internal.StringUtil; /** @@ -25,16 +26,34 @@ public final class MqttConnectPayload { private final String clientIdentifier; private final String willTopic; - private final String willMessage; + private final byte[] willMessage; private final String userName; - private final String password; + private final byte[] password; + /** + * @deprecated use {@link MqttConnectPayload#MqttConnectPayload(String, String, byte[], String, byte[])} instead + */ + @Deprecated public MqttConnectPayload( String clientIdentifier, String willTopic, String willMessage, String userName, String password) { + this( + clientIdentifier, + willTopic, + willMessage.getBytes(CharsetUtil.UTF_8), + userName, + password.getBytes(CharsetUtil.UTF_8)); + } + + public MqttConnectPayload( + String clientIdentifier, + String willTopic, + byte[] willMessage, + String userName, + byte[] password) { this.clientIdentifier = clientIdentifier; this.willTopic = willTopic; this.willMessage = willMessage; @@ -50,7 +69,15 @@ public String willTopic() { return willTopic; } + /** + * @deprecated use {@link MqttConnectPayload#willMessageInBytes()} instead + */ + @Deprecated public String willMessage() { + return new String(willMessage, CharsetUtil.UTF_8); + } + + public byte[] willMessageInBytes() { return willMessage; } @@ -58,7 +85,15 @@ public String userName() { return userName; } + /** + * @deprecated use {@link MqttConnectPayload#passwordInBytes()} instead + */ + @Deprecated public String password() { + return new String(password, CharsetUtil.UTF_8); + } + + public byte[] passwordInBytes() { return password; } diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java index b734c349a09..c8a3546e0ed 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java @@ -339,21 +339,21 @@ private static Result<MqttConnectPayload> decodeConnectionPayload( int numberOfBytesConsumed = decodedClientId.numberOfBytesConsumed; Result<String> decodedWillTopic = null; - Result<String> decodedWillMessage = null; + Result<byte[]> decodedWillMessage = null; if (mqttConnectVariableHeader.isWillFlag()) { decodedWillTopic = decodeString(buffer, 0, 32767); numberOfBytesConsumed += decodedWillTopic.numberOfBytesConsumed; - decodedWillMessage = decodeAsciiString(buffer); + decodedWillMessage = decodeByteArray(buffer); numberOfBytesConsumed += decodedWillMessage.numberOfBytesConsumed; } Result<String> decodedUserName = null; - Result<String> decodedPassword = null; + Result<byte[]> decodedPassword = null; if (mqttConnectVariableHeader.hasUserName()) { decodedUserName = decodeString(buffer); numberOfBytesConsumed += decodedUserName.numberOfBytesConsumed; } if (mqttConnectVariableHeader.hasPassword()) { - decodedPassword = decodeString(buffer); + decodedPassword = decodeByteArray(buffer); numberOfBytesConsumed += decodedPassword.numberOfBytesConsumed; } @@ -419,17 +419,6 @@ private static Result<String> decodeString(ByteBuf buffer) { return decodeString(buffer, 0, Integer.MAX_VALUE); } - private static Result<String> decodeAsciiString(ByteBuf buffer) { - Result<String> result = decodeString(buffer, 0, Integer.MAX_VALUE); - final String s = result.value; - for (int i = 0; i < s.length(); i++) { - if (s.charAt(i) > 127) { - return new Result<String>(null, result.numberOfBytesConsumed); - } - } - return new Result<String>(s, result.numberOfBytesConsumed); - } - private static Result<String> decodeString(ByteBuf buffer, int minBytes, int maxBytes) { final Result<Integer> decodedSize = decodeMsbLsb(buffer); int size = decodedSize.value; @@ -445,6 +434,14 @@ private static Result<String> decodeString(ByteBuf buffer, int minBytes, int max return new Result<String>(s, numberOfBytesConsumed); } + private static Result<byte[]> decodeByteArray(ByteBuf buffer) { + final Result<Integer> decodedSize = decodeMsbLsb(buffer); + int size = decodedSize.value; + byte[] bytes = new byte[size]; + buffer.readBytes(bytes); + return new Result<byte[]>(bytes, decodedSize.numberOfBytesConsumed + size); + } + private static Result<Integer> decodeMsbLsb(ByteBuf buffer) { return decodeMsbLsb(buffer, 0, 65535); } diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java index 4ee7293075e..967cdb844bb 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttEncoder.java @@ -113,8 +113,8 @@ private static ByteBuf encodeConnectMessage( // Will topic and message String willTopic = payload.willTopic(); byte[] willTopicBytes = willTopic != null ? encodeStringUtf8(willTopic) : EmptyArrays.EMPTY_BYTES; - String willMessage = payload.willMessage(); - byte[] willMessageBytes = willMessage != null ? encodeStringUtf8(willMessage) : EmptyArrays.EMPTY_BYTES; + byte[] willMessage = payload.willMessageInBytes(); + byte[] willMessageBytes = willMessage != null ? willMessage : EmptyArrays.EMPTY_BYTES; if (variableHeader.isWillFlag()) { payloadBufferSize += 2 + willTopicBytes.length; payloadBufferSize += 2 + willMessageBytes.length; @@ -126,8 +126,8 @@ private static ByteBuf encodeConnectMessage( payloadBufferSize += 2 + userNameBytes.length; } - String password = payload.password(); - byte[] passwordBytes = password != null ? encodeStringUtf8(password) : EmptyArrays.EMPTY_BYTES; + byte[] password = payload.passwordInBytes(); + byte[] passwordBytes = password != null ? password : EmptyArrays.EMPTY_BYTES; if (variableHeader.hasPassword()) { payloadBufferSize += 2 + passwordBytes.length; } diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java index 51be0072b5b..b893205ee76 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java @@ -17,6 +17,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import io.netty.util.CharsetUtil; import java.util.ArrayList; import java.util.List; @@ -77,9 +78,9 @@ public static final class ConnectBuilder { private boolean willRetain; private MqttQoS willQos = MqttQoS.AT_MOST_ONCE; private String willTopic; - private String willMessage; + private byte[] willMessage; private String username; - private String password; + private byte[] password; ConnectBuilder() { } @@ -119,7 +120,16 @@ public ConnectBuilder willTopic(String willTopic) { return this; } + /** + * @deprecated use {@link ConnectBuilder#willMessage(byte[])} instead + */ + @Deprecated public ConnectBuilder willMessage(String willMessage) { + willMessage(willMessage.getBytes(CharsetUtil.UTF_8)); + return this; + } + + public ConnectBuilder willMessage(byte[] willMessage) { this.willMessage = willMessage; return this; } @@ -145,7 +155,16 @@ public ConnectBuilder username(String username) { return this; } + /** + * @deprecated use {@link ConnectBuilder#password(byte[])} instead + */ + @Deprecated public ConnectBuilder password(String password) { + password(password.getBytes(CharsetUtil.UTF_8)); + return this; + } + + public ConnectBuilder password(byte[] password) { this.hasPassword = true; this.password = password; return this;
diff --git a/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java b/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java index 8bfd2fb95db..21a69055ed5 100644 --- a/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java +++ b/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java @@ -28,6 +28,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -395,7 +396,13 @@ private static void validateConnectPayload(MqttConnectPayload expected, MqttConn actual.clientIdentifier()); assertEquals("MqttConnectPayload UserName mismatch ", expected.userName(), actual.userName()); assertEquals("MqttConnectPayload Password mismatch ", expected.password(), actual.password()); + assertTrue( + "MqttConnectPayload Password bytes mismatch ", + Arrays.equals(expected.passwordInBytes(), actual.passwordInBytes())); assertEquals("MqttConnectPayload WillMessage mismatch ", expected.willMessage(), actual.willMessage()); + assertTrue( + "MqttConnectPayload WillMessage bytes mismatch ", + Arrays.equals(expected.willMessageInBytes(), actual.willMessageInBytes())); assertEquals("MqttConnectPayload WillTopic mismatch ", expected.willTopic(), actual.willTopic()); }
train
train
"2017-06-09T20:34:28"
"2017-05-18T04:14:03Z"
oakad
val
netty/netty/6849_6851
netty/netty
netty/netty/6849
netty/netty/6851
[ "timestamp(timedelta=13.0, similarity=0.8658447283010114)" ]
3f0085c267b5f59a7ca70729e14a18f13581dac2
f5de662f71ebc2bf6af19b659a1a0f8a32a04931
[ "And now I've noticed that the module name's incorrect. I believe it should be `netty-transport-native-unix-common`. Sorry, if that's the case, I should have spotted it when reviewing https://github.com/netty/netty/pull/6740.", "Fixed by https://github.com/netty/netty/pull/6851" ]
[]
"2017-06-13T08:58:06Z"
[ "defect" ]
4.1.12.Final bom uses 4.1.12.Final-SNAPSHOT for the version of netty-transport-unix-common
### Expected behavior The bom provides consistent versions for all of Netty's modules ### Actual behavior netty-transport-unix-common is using a different (and snapshot) version ### Steps to reproduce Import the bom and try to resolve netty-transport-unix-common from Maven Central ### Minimal yet complete reproducer code (or URL to code) N/A ### Netty version 4.1.12.Final ### JVM version (e.g. `java -version`) N/A ### OS version (e.g. `uname -a`) N/A
[ "bom/pom.xml" ]
[ "bom/pom.xml" ]
[]
diff --git a/bom/pom.xml b/bom/pom.xml index a0425e225ea..ed7bffe0579 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -188,8 +188,8 @@ </dependency> <dependency> <groupId>io.netty</groupId> - <artifactId>netty-transport-unix-common</artifactId> - <version>4.1.12.Final-SNAPSHOT</version> + <artifactId>netty-transport-native-unix-common</artifactId> + <version>4.1.13.Final-SNAPSHOT</version> </dependency> <dependency> <groupId>io.netty</groupId>
null
train
train
"2017-06-13T07:43:29"
"2017-06-13T07:59:22Z"
wilkinsona
val
netty/netty/6846_6857
netty/netty
netty/netty/6846
netty/netty/6857
[ "timestamp(timedelta=32.0, similarity=0.9015057496224571)" ]
e597756a56398a73f851f97ac667f3ae198f4545
33b7478b5c157f246708ced77bb2e28c89715ef1
[ "thanks for reporting @normanmaurer! My guess is this will have a measurable impact if the initial size is too small (currently defaults to 32). We reset to the initial array size on each decode operation.", "@Scottmitch agree... I would say we should double up to 512 bytes . WDYT ? I can do a pr", "It will depend upon the use case but can we derive a guess from https://github.com/http2/http_samples or some other sample size? We can start with 512 or 1024 and refine later if you don't have much cycles to investigate.", "@Scottmitch good idea... let me check", "@Scottmitch here you go https://github.com/netty/netty/pull/6857. I think I will have not much time to long into it in more detail so I just used 1024 for now", "1024 sounds like a good start to me ... we can revise/improve later if necessary.", "Fixed by https://github.com/netty/netty/pull/6857" ]
[ "nit: consider using tertiary for less boiler plate:\r\n\r\n```java\r\nfinal int newLength = bytes.length >= 1024 ? bytes.length + initialCapacity : bytes.length << 1;\r\n```", "Consider leaving a comment as to how this value was derived (educated guess, average header length from source X, etc..)", "sure why not", "sure can do" ]
"2017-06-14T10:51:29Z"
[ "improvement" ]
Reconsider growing strategy in HpackHuffmanDecoder
At the moment we just increase my intialCapacity but it may make sense to double it up to a certain size: https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java#L237
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java" ]
[]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java index 307d11a7d53..b49c30d69b5 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanDecoder.java @@ -231,8 +231,11 @@ AsciiString end() throws Http2Exception { private void append(int i) { if (bytes.length == index) { - // Always just expand by INITIAL_SIZE - byte[] newBytes = new byte[bytes.length + initialCapacity]; + // Choose an expanding strategy depending on how big the buffer already is. + // 1024 was choosen as a good guess and we may be able to investigate more if there are better choices. + // See also https://github.com/netty/netty/issues/6846 + final int newLength = bytes.length >= 1024 ? bytes.length + initialCapacity : bytes.length << 1; + byte[] newBytes = new byte[newLength]; System.arraycopy(bytes, 0, newBytes, 0, bytes.length); bytes = newBytes; }
null
val
train
"2017-06-15T06:29:14"
"2017-06-12T18:01:04Z"
normanmaurer
val
netty/netty/6909_6910
netty/netty
netty/netty/6909
netty/netty/6910
[ "timestamp(timedelta=16.0, similarity=0.8987650822178376)" ]
dd69a813d46c2db2b8071445ecddb4bf939ba2e9
faa7b9e82b07be9b8fb1138d6241396c28d7d792
[ "yep but it's public so it cannot be changed until the next major version.", "It can not be changed but we can add a new method and deprecate the old one... let me do in a few minutes ", "Fixed by https://github.com/netty/netty/pull/6910. Please check", "Fixed by https://github.com/netty/netty/pull/6910" ]
[]
"2017-06-27T17:09:09Z"
[]
Typo? EpollSocketChannelConfig.setTcpKeepCntl
https://github.com/netty/netty/blob/3cc405296310643bccddc8c81998c97f25b3201c/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java#L420 shouldn't it be called setTcpKeepCnt?
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java" ]
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java" ]
[]
diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java index 4ac335619b8..eaf2523b980 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollSocketChannelConfig.java @@ -141,7 +141,7 @@ public <T> boolean setOption(ChannelOption<T> option, T value) { } else if (option == EpollChannelOption.TCP_KEEPIDLE) { setTcpKeepIdle((Integer) value); } else if (option == EpollChannelOption.TCP_KEEPCNT) { - setTcpKeepCntl((Integer) value); + setTcpKeepCnt((Integer) value); } else if (option == EpollChannelOption.TCP_KEEPINTVL) { setTcpKeepIntvl((Integer) value); } else if (option == EpollChannelOption.TCP_USER_TIMEOUT) { @@ -415,9 +415,17 @@ public EpollSocketChannelConfig setTcpKeepIntvl(int seconds) { } /** - * Set the {@code TCP_KEEPCNT} option on the socket. See {@code man 7 tcp} for more details. + * @deprecated use {@link #setTcpKeepCnt(int)} */ + @Deprecated public EpollSocketChannelConfig setTcpKeepCntl(int probes) { + return setTcpKeepCnt(probes); + } + + /** + * Set the {@code TCP_KEEPCNT} option on the socket. See {@code man 7 tcp} for more details. + */ + public EpollSocketChannelConfig setTcpKeepCnt(int probes) { try { channel.socket.setTcpKeepCnt(probes); return this;
null
train
train
"2017-06-27T10:53:43"
"2017-06-27T16:25:06Z"
testn
val
netty/netty/6951_6978
netty/netty
netty/netty/6951
netty/netty/6978
[ "timestamp(timedelta=172310.0, similarity=0.8482712342758469)" ]
3e9f617504adb6f3ac984a9320020dd2c202739e
decbbac593edfc3c33c0636181ed996e90f07309
[ "We should check the ref count before writing to the underlying storage. Typically the write/set methods use [checIndex](https://github.com/netty/netty/blob/4.1/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java#L1346) to accomplish this. I'm AFK but can look in more detail later.", "That's a bug... looking now\n\n> Am 07.07.2017 um 15:27 schrieb Scott Mitchell <notifications@github.com>:\n> \n> We should check the ref count before writing to the underlying storage. Typically method use checIndex to accomplish this. I'm AFK but can look in more detail later.\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Ok I have a fix... stay tuned", "@fenik17 please check https://github.com/netty/netty/pull/6953", "@normanmaurer #6953 this is OK. Thanks! But what about this:\r\n> a setCharSequence - the only set method which can increase capacity...\r\n\r\nIMHO, this is not fine.. For example:\r\n```java\r\n ByteBuf buf = Unpooled.directBuffer(1);\r\n buf.setCharSequence(0, \"AB\", CharsetUtil.US_ASCII); // no exception. capacity == 2\r\n\r\n buf.resetWriterIndex().capacity(1);\r\n buf.setBytes(0, new byte[]{1, 2}); // IndexOutOfBoundsException\r\n```\r\nI think only `write` methods should increase capacity.", "> I think only write methods should increase capacity.\r\n\r\nBut if fix it now, someone's code can breaks...", "@fenik17 let me investigate later today. Need to finish some other stuff first.", "@fenik17 you are correct and this is a bug. I have fixed it here: https://github.com/netty/netty/pull/6957. I think its fine to change it here as it is clearly a bug and we can just mention it in the release note to give more visibility.", "@normanmaurer good. Thanks!", "Fixed by https://github.com/netty/netty/pull/6953" ]
[ "this feels backwards, isn't it usually the public method eg. mymethod invoking the private mymethod0?", "@johnou an `ensureAccessible()` method is protected, not is public.", "I was looking at `public int ensureWritable(int minWritableBytes, boolean force)` but it even with the modifier as protected it still feels backwards.", "@johnou you thinks that it's better to move the call of `ensureAccessible` from `ensureWritable0` to `ensureWritable`?", "@johnou there is some sense in this..", "@johnou I think it is fine as otherwise I will need to duplicate some code.", "the implementation of this method may call `checkIndex` but can now call `checkIndex0`. For example `PooledDirectByteBuf#setBytes(..)` and `PooledHeapByteBuf#setBytes(..)` call `checkIndex`. We should inspect all usages of `checkIndex` in buffer implementations which inherit from `AbstractByteBuf` as suggested in https://github.com/netty/netty/pull/6953#discussion_r126544205.", "Discussed with @normanmaurer offline ... both methods are public so we would have to create additional methods that bypass the additional call to ensureWritable (e.g `writeBytes` calls `setBytes0` which calls `checkIndex0`) ... lets not worry about this for now.", "+1... " ]
"2017-07-17T13:46:07Z"
[ "defect" ]
Writing to released ByteBuf
What is the concept of checking the possibility of accessing to `ByteBuf`? Probably a bug. A `writeCharSequence` (`setCharSequence`) can allow writing to released buffer: ```java ByteBuf buf = Unpooled.directBuffer(16); buf.release(); buf.writeCharSequence("1", CharsetUtil.US_ASCII); // <-- no exceptions ``` With an `UnpooledHeapByteBuf` this code leads to `IllegalReferenceCountException` due to call `ensureAccessible()` in the `capacity()`. IIUC this done only to prevent NPE for released buffed. Perhaps it's better to rewrite the method like this: ```java public int capacity() { byte[] array = this.array; if (array != null) { return array.length; } // array is null if refCnt == 0 ensureAccessible(); return 0; } ``` Also, a `setCharSequence` - the only `set` method which can increase capacity...
[ "buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java", "buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java", "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java" ]
[ "buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java", "buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java", "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java" ]
[ "buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java", "buffer/src/test/java/io/netty/buffer/WrappedUnpooledUnsafeByteBufTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java b/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java index a4efb2b97ac..87a512741da 100644 --- a/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java @@ -266,7 +266,8 @@ public ByteBuf ensureWritable(int minWritableBytes) { return this; } - private void ensureWritable0(int minWritableBytes) { + final void ensureWritable0(int minWritableBytes) { + ensureAccessible(); if (minWritableBytes <= writableBytes()) { return; } @@ -286,6 +287,7 @@ private void ensureWritable0(int minWritableBytes) { @Override public int ensureWritable(int minWritableBytes, boolean force) { + ensureAccessible(); if (minWritableBytes < 0) { throw new IllegalArgumentException(String.format( "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); @@ -668,16 +670,16 @@ public ByteBuf setZero(int index, int length) { @Override public int setCharSequence(int index, CharSequence sequence, Charset charset) { if (charset.equals(CharsetUtil.UTF_8)) { - ensureWritable(ByteBufUtil.utf8MaxBytes(sequence)); + ensureWritable0(ByteBufUtil.utf8MaxBytes(sequence)); return ByteBufUtil.writeUtf8(this, index, sequence, sequence.length()); } if (charset.equals(CharsetUtil.US_ASCII) || charset.equals(CharsetUtil.ISO_8859_1)) { int len = sequence.length(); - ensureWritable(len); + ensureWritable0(len); return ByteBufUtil.writeAscii(this, index, sequence, len); } byte[] bytes = sequence.toString().getBytes(charset); - ensureWritable(bytes.length); + ensureWritable0(bytes.length); setBytes(index, bytes); return bytes.length; } @@ -934,7 +936,6 @@ public ByteBuf writeBoolean(boolean value) { @Override public ByteBuf writeByte(int value) { - ensureAccessible(); ensureWritable0(1); _setByte(writerIndex++, value); return this; @@ -942,7 +943,6 @@ public ByteBuf writeByte(int value) { @Override public ByteBuf writeShort(int value) { - ensureAccessible(); ensureWritable0(2); _setShort(writerIndex, value); writerIndex += 2; @@ -951,7 +951,6 @@ public ByteBuf writeShort(int value) { @Override public ByteBuf writeShortLE(int value) { - ensureAccessible(); ensureWritable0(2); _setShortLE(writerIndex, value); writerIndex += 2; @@ -960,7 +959,6 @@ public ByteBuf writeShortLE(int value) { @Override public ByteBuf writeMedium(int value) { - ensureAccessible(); ensureWritable0(3); _setMedium(writerIndex, value); writerIndex += 3; @@ -969,7 +967,6 @@ public ByteBuf writeMedium(int value) { @Override public ByteBuf writeMediumLE(int value) { - ensureAccessible(); ensureWritable0(3); _setMediumLE(writerIndex, value); writerIndex += 3; @@ -978,7 +975,6 @@ public ByteBuf writeMediumLE(int value) { @Override public ByteBuf writeInt(int value) { - ensureAccessible(); ensureWritable0(4); _setInt(writerIndex, value); writerIndex += 4; @@ -987,7 +983,6 @@ public ByteBuf writeInt(int value) { @Override public ByteBuf writeIntLE(int value) { - ensureAccessible(); ensureWritable0(4); _setIntLE(writerIndex, value); writerIndex += 4; @@ -996,7 +991,6 @@ public ByteBuf writeIntLE(int value) { @Override public ByteBuf writeLong(long value) { - ensureAccessible(); ensureWritable0(8); _setLong(writerIndex, value); writerIndex += 8; @@ -1005,7 +999,6 @@ public ByteBuf writeLong(long value) { @Override public ByteBuf writeLongLE(long value) { - ensureAccessible(); ensureWritable0(8); _setLongLE(writerIndex, value); writerIndex += 8; @@ -1032,7 +1025,6 @@ public ByteBuf writeDouble(double value) { @Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - ensureAccessible(); ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; @@ -1064,7 +1056,6 @@ public ByteBuf writeBytes(ByteBuf src, int length) { @Override public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { - ensureAccessible(); ensureWritable(length); setBytes(writerIndex, src, srcIndex, length); writerIndex += length; @@ -1073,9 +1064,8 @@ public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { @Override public ByteBuf writeBytes(ByteBuffer src) { - ensureAccessible(); int length = src.remaining(); - ensureWritable(length); + ensureWritable0(length); setBytes(writerIndex, src); writerIndex += length; return this; @@ -1084,7 +1074,6 @@ public ByteBuf writeBytes(ByteBuffer src) { @Override public int writeBytes(InputStream in, int length) throws IOException { - ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { @@ -1095,7 +1084,6 @@ public int writeBytes(InputStream in, int length) @Override public int writeBytes(ScatteringByteChannel in, int length) throws IOException { - ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { @@ -1106,7 +1094,6 @@ public int writeBytes(ScatteringByteChannel in, int length) throws IOException { @Override public int writeBytes(FileChannel in, long position, int length) throws IOException { - ensureAccessible(); ensureWritable(length); int writtenBytes = setBytes(writerIndex, in, position, length); if (writtenBytes > 0) { @@ -1123,7 +1110,7 @@ public ByteBuf writeZero(int length) { ensureWritable(length); int wIndex = writerIndex; - checkIndex(wIndex, length); + checkIndex0(wIndex, length); int nLong = length >>> 3; int nBytes = length & 7; diff --git a/buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java b/buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java index 6d9667c7de4..d5e9239cabc 100644 --- a/buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/AbstractUnsafeSwappedByteBuf.java @@ -122,7 +122,7 @@ public final ByteBuf setDouble(int index, double value) { @Override public final ByteBuf writeShort(int value) { - wrapped.ensureWritable(2); + wrapped.ensureWritable0(2); _setShort(wrapped, wrapped.writerIndex, nativeByteOrder ? (short) value : Short.reverseBytes((short) value)); wrapped.writerIndex += 2; return this; @@ -130,7 +130,7 @@ public final ByteBuf writeShort(int value) { @Override public final ByteBuf writeInt(int value) { - wrapped.ensureWritable(4); + wrapped.ensureWritable0(4); _setInt(wrapped, wrapped.writerIndex, nativeByteOrder ? value : Integer.reverseBytes(value)); wrapped.writerIndex += 4; return this; @@ -138,7 +138,7 @@ public final ByteBuf writeInt(int value) { @Override public final ByteBuf writeLong(long value) { - wrapped.ensureWritable(8); + wrapped.ensureWritable0(8); _setLong(wrapped, wrapped.writerIndex, nativeByteOrder ? value : Long.reverseBytes(value)); wrapped.writerIndex += 8; return this; diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index 86898c686d3..8f6c5f33d1e 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -482,7 +482,7 @@ public static int writeUtf8(ByteBuf buf, CharSequence seq) { for (;;) { if (buf instanceof AbstractByteBuf) { AbstractByteBuf byteBuf = (AbstractByteBuf) buf; - byteBuf.ensureWritable(utf8MaxBytes(seq)); + byteBuf.ensureWritable0(utf8MaxBytes(seq)); int written = writeUtf8(byteBuf, byteBuf.writerIndex, seq, seq.length()); byteBuf.writerIndex += written; return written; @@ -583,7 +583,7 @@ public static int writeAscii(ByteBuf buf, CharSequence seq) { for (;;) { if (buf instanceof AbstractByteBuf) { AbstractByteBuf byteBuf = (AbstractByteBuf) buf; - byteBuf.ensureWritable(len); + byteBuf.ensureWritable0(len); int written = writeAscii(byteBuf, byteBuf.writerIndex, seq, len); byteBuf.writerIndex += written; return written; diff --git a/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java index 242a653a3dd..1dcc3702c4b 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledUnsafeDirectByteBuf.java @@ -374,7 +374,8 @@ protected SwappedByteBuf newSwappedByteBuf() { @Override public ByteBuf setZero(int index, int length) { - UnsafeByteBufUtil.setZero(this, addr(index), index, length); + checkIndex(index, length); + UnsafeByteBufUtil.setZero(addr(index), length); return this; } @@ -382,7 +383,7 @@ public ByteBuf setZero(int index, int length) { public ByteBuf writeZero(int length) { ensureWritable(length); int wIndex = writerIndex; - setZero(wIndex, length); + UnsafeByteBufUtil.setZero(addr(wIndex), length); writerIndex = wIndex + length; return this; } diff --git a/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java index d06e02f0bcc..a644450f5ce 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledUnsafeHeapByteBuf.java @@ -131,8 +131,9 @@ protected void _setLongLE(int index, long value) { @Override public ByteBuf setZero(int index, int length) { if (PlatformDependent.javaVersion() >= 7) { + checkIndex(index, length); // Only do on java7+ as the needed Unsafe call was only added there. - _setZero(index, length); + UnsafeByteBufUtil.setZero(memory, idx(index), length); return this; } return super.setZero(index, length); @@ -144,18 +145,13 @@ public ByteBuf writeZero(int length) { // Only do on java7+ as the needed Unsafe call was only added there. ensureWritable(length); int wIndex = writerIndex; - _setZero(wIndex, length); + UnsafeByteBufUtil.setZero(memory, idx(wIndex), length); writerIndex = wIndex + length; return this; } return super.writeZero(length); } - private void _setZero(int index, int length) { - checkIndex(index, length); - UnsafeByteBufUtil.setZero(memory, idx(index), length); - } - @Override @Deprecated protected SwappedByteBuf newSwappedByteBuf() { diff --git a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java index e2637b0f439..07bd76b80b2 100644 --- a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeDirectByteBuf.java @@ -517,7 +517,8 @@ protected SwappedByteBuf newSwappedByteBuf() { @Override public ByteBuf setZero(int index, int length) { - UnsafeByteBufUtil.setZero(this, addr(index), index, length); + checkIndex(index, length); + UnsafeByteBufUtil.setZero(addr(index), length); return this; } @@ -525,7 +526,7 @@ public ByteBuf setZero(int index, int length) { public ByteBuf writeZero(int length) { ensureWritable(length); int wIndex = writerIndex; - setZero(wIndex, length); + UnsafeByteBufUtil.setZero(addr(wIndex), length); writerIndex = wIndex + length; return this; } diff --git a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java index b88577cb6c0..51786f1567c 100644 --- a/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/UnpooledUnsafeHeapByteBuf.java @@ -245,7 +245,8 @@ protected void _setLongLE(int index, long value) { public ByteBuf setZero(int index, int length) { if (PlatformDependent.javaVersion() >= 7) { // Only do on java7+ as the needed Unsafe call was only added there. - _setZero(index, length); + checkIndex(index, length); + UnsafeByteBufUtil.setZero(array, index, length); return this; } return super.setZero(index, length); @@ -257,18 +258,13 @@ public ByteBuf writeZero(int length) { // Only do on java7+ as the needed Unsafe call was only added there. ensureWritable(length); int wIndex = writerIndex; - _setZero(wIndex, length); + UnsafeByteBufUtil.setZero(array, wIndex, length); writerIndex = wIndex + length; return this; } return super.writeZero(length); } - private void _setZero(int index, int length) { - checkIndex(index, length); - UnsafeByteBufUtil.setZero(array, index, length); - } - @Override @Deprecated protected SwappedByteBuf newSwappedByteBuf() { diff --git a/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java index 332600d66ce..95c68a02942 100644 --- a/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java @@ -581,12 +581,11 @@ static void getBytes(AbstractByteBuf buf, long addr, int index, OutputStream out } } - static void setZero(AbstractByteBuf buf, long addr, int index, int length) { + static void setZero(long addr, int length) { if (length == 0) { return; } - buf.checkIndex(index, length); PlatformDependent.setMemory(addr, length, ZERO); }
diff --git a/buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java b/buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java index 641d3426469..410f21aad3d 100644 --- a/buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/SlicedByteBufTest.java @@ -94,18 +94,6 @@ public void testNioBufferExposeOnlyRegion() { super.testNioBufferExposeOnlyRegion(); } - @Test(expected = IndexOutOfBoundsException.class) - @Override - public void testEnsureWritableAfterRelease() { - super.testEnsureWritableAfterRelease(); - } - - @Test(expected = IndexOutOfBoundsException.class) - @Override - public void testWriteZeroAfterRelease() throws IOException { - super.testWriteZeroAfterRelease(); - } - @Test(expected = IndexOutOfBoundsException.class) @Override public void testGetReadOnlyDirectDst() { diff --git a/buffer/src/test/java/io/netty/buffer/WrappedUnpooledUnsafeByteBufTest.java b/buffer/src/test/java/io/netty/buffer/WrappedUnpooledUnsafeByteBufTest.java index 88c2a0c2511..e8c0ed0746c 100644 --- a/buffer/src/test/java/io/netty/buffer/WrappedUnpooledUnsafeByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/WrappedUnpooledUnsafeByteBufTest.java @@ -88,18 +88,6 @@ public void testNioBufferExposeOnlyRegion() { super.testNioBufferExposeOnlyRegion(); } - @Test(expected = IndexOutOfBoundsException.class) - @Override - public void testEnsureWritableAfterRelease() { - super.testEnsureWritableAfterRelease(); - } - - @Test(expected = IndexOutOfBoundsException.class) - @Override - public void testWriteZeroAfterRelease() throws IOException { - super.testWriteZeroAfterRelease(); - } - @Test(expected = IndexOutOfBoundsException.class) @Override public void testGetReadOnlyDirectDst() {
train
train
"2017-07-18T13:25:12"
"2017-07-06T20:49:31Z"
fenik17
val
netty/netty/6968_6982
netty/netty
netty/netty/6968
netty/netty/6982
[ "timestamp(timedelta=55439.0, similarity=0.8439824231223864)" ]
e6a399a7785b41dc941e8037257a30a0df1d92d4
06e16a2c85800492fbc1f1211a0f9a5e37d0c163
[ "@nayato can you submit a pr with something that you think makes things more clear ?", "@nayato - please check if https://github.com/netty/netty/pull/6982 is what you had in mind.", "@nayato does https://github.com/netty/netty/pull/6987 work for you ?", "Fixed by https://github.com/netty/netty/pull/6987" ]
[]
"2017-07-18T07:05:35Z"
[ "defect", "improvement" ]
TlsReadTest tests are misleading
Tests rely on channel having AutoRead = false and verify that read was issued through setting readIssued. In reality read method is called during construction of EmbeddedChannel - because AutoRead is true at this time, before AutoRead is set to false in test.
[ "transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java" ]
[ "transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java b/transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java index 2dcb577deb7..58302c60bbb 100644 --- a/transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java +++ b/transport/src/main/java/io/netty/channel/embedded/EmbeddedChannel.java @@ -18,6 +18,7 @@ import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayDeque; +import java.util.Map; import java.util.Queue; import io.netty.channel.AbstractChannel; @@ -29,6 +30,7 @@ import io.netty.channel.ChannelId; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelMetadata; +import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; @@ -121,6 +123,20 @@ public EmbeddedChannel(ChannelId channelId, final ChannelHandler... handlers) { this(channelId, false, handlers); } + /** + * Create a new instance with the channel options applied and the pipeline initialized with the specified handlers. + * + * @param options {@link ChannelOption}s that will be applied before the handlers are initialized. + * @param handlers the {@link ChannelHandler}s which will be add in the {@link ChannelPipeline} + */ + public EmbeddedChannel(Map<ChannelOption<?>, ?> options, final ChannelHandler... handlers) { + super(null, EmbeddedChannelId.INSTANCE); + metadata = metadata(false); + config = new DefaultChannelConfig(this); + this.config.setOptions(options); + setup(handlers); + } + /** * Create a new instance with the channel ID set to the given ID and the pipeline * initialized with the specified handlers.
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java index 84559a76407..d67986abfca 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -27,6 +27,7 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.EventLoopGroup; import io.netty.channel.embedded.EmbeddedChannel; @@ -55,10 +56,13 @@ import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; + import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; @@ -160,28 +164,32 @@ public void read(ChannelHandlerContext ctx) throws Exception { } public void test(final boolean dropChannelActive) throws Exception { - SSLEngine engine = SSLContext.getDefault().createSSLEngine(); - engine.setUseClientMode(true); - - EmbeddedChannel ch = new EmbeddedChannel( - this, - new SslHandler(engine), - new ChannelInboundHandlerAdapter() { - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - if (!dropChannelActive) { - ctx.fireChannelActive(); - } - } - } - ); - ch.config().setAutoRead(false); - assertFalse(ch.config().isAutoRead()); - - assertTrue(ch.writeOutbound(Unpooled.EMPTY_BUFFER)); - assertTrue(readIssued); - assertTrue(ch.finishAndReleaseAll()); - } + SSLEngine engine = SSLContext.getDefault().createSSLEngine(); + engine.setUseClientMode(true); + + Map<ChannelOption<?>, Object> options = new HashMap<ChannelOption<?>, Object>(); + options.put(ChannelOption.AUTO_READ, false); + EmbeddedChannel ch = new EmbeddedChannel( + options, + this, + new SslHandler(engine), + new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + if (!dropChannelActive) { + ctx.fireChannelActive(); + } + } + } + ); + assertFalse(ch.config().isAutoRead()); + assertTrue(readIssued); + readIssued = false; + + assertTrue(ch.writeOutbound(Unpooled.EMPTY_BUFFER)); + assertTrue(readIssued); + assertTrue(ch.finishAndReleaseAll()); + } } @Test
test
train
"2017-07-18T07:24:04"
"2017-07-13T22:02:25Z"
nayato
val
netty/netty/6984_6985
netty/netty
netty/netty/6984
netty/netty/6985
[ "timestamp(timedelta=5.0, similarity=1.0)" ]
0ad99310f5c02363f9402872d9b3d803654a794d
3952673f170478a1d9f04d5d50cb76a94b134e09
[ "Fixed by https://github.com/netty/netty/pull/6985" ]
[]
"2017-07-18T10:30:33Z"
[ "defect" ]
MQTT unknown message type isn't handled as decoding error
### Expected behavior When there is an MQTT decoding error, an invalidMessage is created and a DecodeResult with failure and related cause exception is filled with right information so that the user application can see what's the problem. It should happens in any step in the decoding phase. ### Actual behavior It doesn't work if the problem is in the fixed header with a not valid MQTT message type. Poisoning a message with the first byte set to 0xF0 (so 15 that is not a valid MQTT message type), the IllegalArgumentException is raised and propagated. There is no way to have a failed DecodeResult as in the other scenarios. ### Steps to reproduce Building a server pipeline with the MqttDecoder and then after opening the connection sending a packet with just two bytes 0xF0 0x00. ### Netty version 4.1.13 Final ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java" ]
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java" ]
[ "codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java" ]
diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java index c8a3546e0ed..8d94ee48e96 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java @@ -71,11 +71,15 @@ public MqttDecoder(int maxBytesInMessage) { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { switch (state()) { - case READ_FIXED_HEADER: + case READ_FIXED_HEADER: try { mqttFixedHeader = decodeFixedHeader(buffer); bytesRemainingInVariablePart = mqttFixedHeader.remainingLength(); checkpoint(DecoderState.READ_VARIABLE_HEADER); // fall through + } catch (Exception cause) { + out.add(invalidMessage(cause)); + return; + } case READ_VARIABLE_HEADER: try { if (bytesRemainingInVariablePart > maxBytesInMessage) {
diff --git a/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java b/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java index 21a69055ed5..dd6c74269fa 100644 --- a/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java +++ b/codec-mqtt/src/test/java/io/netty/handler/codec/mqtt/MqttCodecTest.java @@ -239,6 +239,29 @@ public void testDisconnectMessage() throws Exception { testMessageWithOnlyFixedHeader(MqttMessageType.DISCONNECT); } + @Test + public void testUnknownMessageType() throws Exception { + + final MqttMessage message = createMessageWithFixedHeader(MqttMessageType.PINGREQ); + ByteBuf byteBuf = MqttEncoder.doEncode(ALLOCATOR, message); + try { + // setting an invalid message type (15, reserved and forbidden by MQTT 3.1.1 spec) + byteBuf.setByte(0, 0xF0); + final List<Object> out = new LinkedList<Object>(); + mqttDecoder.decode(ctx, byteBuf, out); + + assertEquals("Expected one object but got " + out.size(), 1, out.size()); + + final MqttMessage decodedMessage = (MqttMessage) out.get(0); + assertTrue(decodedMessage.decoderResult().isFailure()); + Throwable cause = decodedMessage.decoderResult().cause(); + assertTrue(cause instanceof IllegalArgumentException); + assertEquals("unknown message type: 15", cause.getMessage()); + } finally { + byteBuf.release(); + } + } + private void testMessageWithOnlyFixedHeader(MqttMessageType messageType) throws Exception { MqttMessage message = createMessageWithFixedHeader(messageType); ByteBuf byteBuf = MqttEncoder.doEncode(ALLOCATOR, message);
train
train
"2017-07-18T09:28:56"
"2017-07-18T10:26:33Z"
ppatierno
val
netty/netty/5478_6991
netty/netty
netty/netty/5478
netty/netty/6991
[ "timestamp(timedelta=1125.0, similarity=0.8645560119075416)" ]
0afe4e09643c457c452ef0d9563c46f8e7c24ad1
bb22bd8e7a8db6a7139dff4893fd9015b0796c71
[ "Can you provide a PR with the test and a fix?\n\n> Am 30.06.2016 um 16:49 schrieb Benjamin Fiorini notifications@github.com:\n> \n> Hello,\n> \n> There is a bug in the nextChunk() algorithm of the HttpPostRequestEncoder. When chunking a big request or multipart data, if the size of the resulting query is a multiple of the chunk size, isLastChunkSent is not set to true at the end, resulting in a NullPointerException.\n> \n> This bug is present in version 3.10 as well as 4.x\n> \n> Here is a unitest that shows this problem:\n> \n> ```\n> @Test\n> public void testNpe() throws Exception {\n> DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,\n> HttpMethod.POST, \"http://localhost\");\n> HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true);\n> int length = 7943;\n> char[] array = new char[length];\n> Arrays.fill(array, 'a');\n> String longText = new String(array);\n> encoder.addBodyAttribute(\"foo\", longText);\n> encoder.finalizeRequest();\n> \n> while (! encoder.isEndOfInput()) {\n> encoder.readChunk((ByteBufAllocator) null);\n> }\n> }\n> ```\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n", "@bfiorini any interest in provide a fix as PR with a unit test ?\n", "On my side, not able to reproduce it. As far as I read the code, if the data is a multiple of chunk size, the next call will set to true the isLastChunk and returns LastHttpContent.EMPTY_LAST_CONTENT (as defined in the API).\r\n\r\nMaybe I'm missing something?", "For those interested here is a test case that reproduces on `4.1.8.Final`\r\n\r\n```java\r\n@Test\r\npublic void test() throws Exception {\r\n DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);\r\n DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, \"http://localhost\");\r\n HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory, request, true, HttpConstants.DEFAULT_CHARSET, HttpPostRequestEncoder.EncoderMode.RFC1738);\r\n\r\n MemoryFileUpload first = new MemoryFileUpload(\"resources\", \"\", \"application/json\", null, Charset.forName(\"UTF-8\"), -1);\r\n first.setMaxSize(-1);\r\n first.setContent(new ByteArrayInputStream(new byte[7955]));\r\n encoder.addBodyHttpData(first);\r\n\r\n MemoryFileUpload second = new MemoryFileUpload(\"resources2\", \"\", \"application/json\", null, Charset.forName(\"UTF-8\"), -1);\r\n second.setMaxSize(-1);\r\n second.setContent(new ByteArrayInputStream(new byte[7955]));\r\n encoder.addBodyHttpData(second);\r\n\r\n encoder.finalizeRequest();\r\n assertEquals(\"First chunk is not 8096 bytes\", 8096, encoder.readChunk((ByteBufAllocator) null).content().readableBytes());\r\n assertFalse(\"Already at end of input\", encoder.isEndOfInput());\r\n encoder.readChunk((ByteBufAllocator) null);\r\n}\r\n```", "Fixed by https://github.com/netty/netty/pull/6991" ]
[ "call `httpContent.release()`", "call httpContent.release()", "static", "done", "done", "done" ]
"2017-07-19T07:53:36Z"
[ "defect" ]
NullPointerException in HttpPostRequestEncoder
Hello, There is a bug in the `nextChunk()` algorithm of the `HttpPostRequestEncoder`. When chunking a big request or multipart data, if the size of the resulting query is a multiple of the chunk size, `isLastChunkSent` is not set to `true` at the end, resulting in a NullPointerException. This bug is present in version 3.10 as well as 4.x Here is a unitest that shows this problem: ``` java @Test public void testNpe() throws Exception { DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost"); HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true); int length = 7943; char[] array = new char[length]; Arrays.fill(array, 'a'); String longText = new String(array); encoder.addBodyAttribute("foo", longText); encoder.finalizeRequest(); while (! encoder.isEndOfInput()) { encoder.readChunk((ByteBufAllocator) null); } } ```
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java index 57f81f5b66b..a56431e2226 100755 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java @@ -1062,40 +1062,30 @@ private HttpContent nextChunk() throws ErrorDataEncoderException { isLastChunkSent = true; return LastHttpContent.EMPTY_LAST_CONTENT; } - ByteBuf buffer; - int size = HttpPostBodyUtil.chunkSize; // first test if previous buffer is not empty - if (currentBuffer != null) { - size -= currentBuffer.readableBytes(); - } + int size = calculateRemainingSize(); if (size <= 0) { // NextChunk from buffer - buffer = fillByteBuf(); + ByteBuf buffer = fillByteBuf(); return new DefaultHttpContent(buffer); } // size > 0 if (currentData != null) { // continue to read data + HttpContent chunk; if (isMultipart) { - HttpContent chunk = encodeNextChunkMultipart(size); - if (chunk != null) { - return chunk; - } + chunk = encodeNextChunkMultipart(size); } else { - HttpContent chunk = encodeNextChunkUrlEncoded(size); - if (chunk != null) { - // NextChunk Url from currentData - return chunk; - } + chunk = encodeNextChunkUrlEncoded(size); + } + if (chunk != null) { + // NextChunk from data + return chunk; } - size = HttpPostBodyUtil.chunkSize - currentBuffer.readableBytes(); + size = calculateRemainingSize(); } if (!iterator.hasNext()) { - isLastChunk = true; - // NextChunk as last non empty from buffer - buffer = currentBuffer; - currentBuffer = null; - return new DefaultHttpContent(buffer); + return lastChunk(); } while (size > 0 && iterator.hasNext()) { currentData = iterator.next(); @@ -1107,21 +1097,33 @@ private HttpContent nextChunk() throws ErrorDataEncoderException { } if (chunk == null) { // not enough - size = HttpPostBodyUtil.chunkSize - currentBuffer.readableBytes(); + size = calculateRemainingSize(); continue; } // NextChunk from data return chunk; } // end since no more data + return lastChunk(); + } + + private int calculateRemainingSize() { + int size = HttpPostBodyUtil.chunkSize; + if (currentBuffer != null) { + size -= currentBuffer.readableBytes(); + } + return size; + } + + private HttpContent lastChunk() { isLastChunk = true; if (currentBuffer == null) { isLastChunkSent = true; // LastChunk with no more data return LastHttpContent.EMPTY_LAST_CONTENT; } - // Previous LastChunk with no more data - buffer = currentBuffer; + // NextChunk as last non empty from buffer + ByteBuf buffer = currentBuffer; currentBuffer = null; return new DefaultHttpContent(buffer); }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java index 3a206f44ba7..2d821273fa8 100755 --- a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoderTest.java @@ -19,16 +19,20 @@ import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.HttpConstants; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.EncoderMode; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder.ErrorDataEncoderException; import io.netty.util.CharsetUtil; import io.netty.util.internal.StringUtil; import org.junit.Test; +import java.io.ByteArrayInputStream; import java.io.File; +import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; @@ -37,6 +41,7 @@ import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TRANSFER_ENCODING; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -358,4 +363,64 @@ private static String getRequestBody(HttpPostRequestEncoder encoder) throws Exce content.release(); return contentStr; } + + @Test + public void testDataIsMultipleOfChunkSize1() throws Exception { + DefaultHttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, + HttpMethod.POST, "http://localhost"); + HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory, request, true, + HttpConstants.DEFAULT_CHARSET, HttpPostRequestEncoder.EncoderMode.RFC1738); + + MemoryFileUpload first = new MemoryFileUpload("resources", "", "application/json", null, + Charset.forName("UTF-8"), -1); + first.setMaxSize(-1); + first.setContent(new ByteArrayInputStream(new byte[7955])); + encoder.addBodyHttpData(first); + + MemoryFileUpload second = new MemoryFileUpload("resources2", "", "application/json", null, + Charset.forName("UTF-8"), -1); + second.setMaxSize(-1); + second.setContent(new ByteArrayInputStream(new byte[7928])); + encoder.addBodyHttpData(second); + + assertNotNull(encoder.finalizeRequest()); + + checkNextChunkSize(encoder, 8096); + checkNextChunkSize(encoder, 8096); + + HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null); + assertTrue("Expected LastHttpContent is not received", httpContent instanceof LastHttpContent); + httpContent.release(); + + assertTrue("Expected end of input is not receive", encoder.isEndOfInput()); + } + + @Test + public void testDataIsMultipleOfChunkSize2() throws Exception { + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, + HttpMethod.POST, "http://localhost"); + HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(request, true); + int length = 7943; + char[] array = new char[length]; + Arrays.fill(array, 'a'); + String longText = new String(array); + encoder.addBodyAttribute("foo", longText); + + assertNotNull(encoder.finalizeRequest()); + + checkNextChunkSize(encoder, 8096); + + HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null); + assertTrue("Expected LastHttpContent is not received", httpContent instanceof LastHttpContent); + httpContent.release(); + + assertTrue("Expected end of input is not receive", encoder.isEndOfInput()); + } + + private static void checkNextChunkSize(HttpPostRequestEncoder encoder, int expectedSize) throws Exception { + HttpContent httpContent = encoder.readChunk((ByteBufAllocator) null); + assertEquals("Chunk is not " + expectedSize + " bytes", expectedSize, httpContent.content().readableBytes()); + httpContent.release(); + } }
train
train
"2017-07-19T07:59:56"
"2016-06-30T14:49:50Z"
bfiorini
val
netty/netty/6993_6994
netty/netty
netty/netty/6993
netty/netty/6994
[ "timestamp(timedelta=225.0, similarity=0.9252722530631794)" ]
a91df58ca17d5b30c57c46dde5b1d60bb659b029
85da3a22b7d30bc63ea3528dfc4d4243f33e6ad9
[ "@Scottmitch please remember to set the milestone when you close issues so it is listed for the correct version." ]
[ "Please address the TODO ", "Or just remove the fprintf for now", "Please revert these changes as it seems this just moves code and so is not related", "IIUC the static methods have to move up to avoid their first use case or we need to declare the method before the first use.", "IIUC this method doesn't have to move (it isn't static and is declared in the header file)?", "Why do we want to suppress the error here? `socket_type` accounts for `EAFNOSUPPORT` so if we get it here it seems like a programming error. Can we just propagate the error via `netty_unix_socket_setOptionHandleError` in this case too?", "netty_unix_socket_setOption0 needs to be defined before _socket() uses it, and I wanted to keep most of these functions together. \r\n\r\nI can move the minimal number of functions to do so, or move _socket down. Preference?", "done.", "Moving just the static methods sgtm", "Why do we want to suppress the error here? socket_type accounts for EAFNOSUPPORT so if we get it here it seems like a programming error. Can we just propagate the error via netty_unix_socket_setOptionHandleError in this case too?", "This was collapsed in https://github.com/netty/netty/pull/6994#discussion_r128362622", "Sure, it doesn't have to, but some teams prefer to keep related code adjacent / contiguous if possible. If you don't have such a requirement I can move the bare minimum.", "That code checks if AF_INET6 is allowed, but not dual stack mode which is what `_socket()` is asking for.", "Done.", "Can we remote the `if` since it doesn't do anything? What about the following:\r\n\r\n```c\r\nif (errno != EAFNOSUPPORT) {\r\n...\r\n}\r\n// else we failed to enable dual stack mode.\r\n// It is assumed the socket is re‐stricted to sending and receiving IPv6 packets only.\r\n```", "Done." ]
"2017-07-19T20:20:09Z"
[ "defect", "improvement" ]
Netty Epoll fails in IPv6 only environment
https://github.com/netty/netty/blob/83de77fbe5385130ba9afc666fecbe9b59bd8032/transport-native-unix-common/src/main/c/netty_unix_socket.c#L198 In this code, it tries to set dual stack sockets, but fails when running in an IPv6 only environment. Such an environment exists in Google by blocking all IPv4 functionality in the kernel in order to prove code is IPv6 compatible. cc: @pmarks-net
[ "transport-native-unix-common/src/main/c/netty_unix_socket.c" ]
[ "transport-native-unix-common/src/main/c/netty_unix_socket.c" ]
[]
diff --git a/transport-native-unix-common/src/main/c/netty_unix_socket.c b/transport-native-unix-common/src/main/c/netty_unix_socket.c index 2cfb5e4d7d5..519f701c839 100644 --- a/transport-native-unix-common/src/main/c/netty_unix_socket.c +++ b/transport-native-unix-common/src/main/c/netty_unix_socket.c @@ -188,17 +188,40 @@ static int socket_type(JNIEnv* env) { } } +static void netty_unix_socket_optionHandleError(JNIEnv* env, int err, char* method) { + if (err == EBADF) { + netty_unix_errors_throwClosedChannelException(env); + } else { + netty_unix_errors_throwChannelExceptionErrorNo(env, method, err); + } +} + +static void netty_unix_socket_setOptionHandleError(JNIEnv* env, int err) { + netty_unix_socket_optionHandleError(env, err, "setsockopt() failed: "); +} + +static int netty_unix_socket_setOption0(jint fd, int level, int optname, const void* optval, socklen_t len) { + return setsockopt(fd, level, optname, optval, len); +} + static jint _socket(JNIEnv* env, jclass clazz, int type) { int fd = nettyNonBlockingSocket(socketType, type, 0); if (fd == -1) { return -errno; } else if (socketType == AF_INET6) { - // Allow to listen /connect ipv4 and ipv6 + // Try to allow listen /connect ipv4 and ipv6 int optval = 0; - if (netty_unix_socket_setOption(env, fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)) < 0) { - // Something went wrong so close the fd and return here. setOption(...) itself throws the exception already. - close(fd); - return -1; + if (netty_unix_socket_setOption0(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)) < 0) { + if (errno != EAFNOSUPPORT) { + netty_unix_socket_setOptionHandleError(env, errno); + // Something went wrong so close the fd and return here. setOption(...) itself throws the exception already. + close(fd); + return -1; + } + // else we failed to enable dual stack mode. + // It is assumed the socket is re‐stricted to sending and receiving IPv6 packets only. + // Don't close fd and don't return -1. At best we can do is log. + // TODO: bubble this up to an actual Logger. } } return fd; @@ -289,26 +312,10 @@ static jobject _recvFrom(JNIEnv* env, jint fd, void* buffer, jint pos, jint limi return createDatagramSocketAddress(env, &addr, res); } -static void netty_unix_socket_optionHandleError(JNIEnv* env, int err, char* method) { - if (err == EBADF) { - netty_unix_errors_throwClosedChannelException(env); - } else { - netty_unix_errors_throwChannelExceptionErrorNo(env, method, err); - } -} - -static void netty_unix_socket_setOptionHandleError(JNIEnv* env, int err) { - netty_unix_socket_optionHandleError(env, err, "setsockopt() failed: "); -} - static void netty_unix_socket_getOptionHandleError(JNIEnv* env, int err) { netty_unix_socket_optionHandleError(env, err, "getsockopt() failed: "); } -static int netty_unix_socket_setOption0(jint fd, int level, int optname, const void* optval, socklen_t len) { - return setsockopt(fd, level, optname, optval, len); -} - static int netty_unix_socket_getOption0(jint fd, int level, int optname, void* optval, socklen_t optlen) { return getsockopt(fd, level, optname, optval, &optlen); }
null
val
train
"2017-07-19T22:37:23"
"2017-07-19T20:19:28Z"
carl-mastrangelo
val
netty/netty/6998_6999
netty/netty
netty/netty/6998
netty/netty/6999
[ "timestamp(timedelta=18.0, similarity=0.8677490189405712)" ]
f23b2fc25d05134ce9a3811043df274ee4685720
fbd0b3f3ca3b8f80335a881782e73602bfd2b6a9
[ "@MartyIX yes... Can you please open a PR with a fix ?", "Yes, https://github.com/netty/netty/pull/6999", "Fixes by https://github.com/netty/netty/pull/6999 . @MartyIX thanks" ]
[ "![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Replace this usage of System.out or System.err by a logger. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=squid%3AS106)\n", "![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Replace this usage of System.out or System.err by a logger. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=squid%3AS106)\n", "@normanmaurer Is it necessary to replace it? The code is an example. It's easier to grab code with println and run it somewhere without configuring of a logger..", "I think its fine as we also use println for the success case", "@normanmaurer OK. So what should I do next to get this pull request merged?", "nothing... I will merge soon." ]
"2017-07-20T10:16:58Z"
[ "defect" ]
Websocket example and WebSocketHandshakeException
Hi, Websocket example contains the following code: if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } (https://github.com/netty/netty/blob/4.1/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java#L85) The problem I've encountered is that `finishHandshake` may throw `WebSocketHandshakeException` exception. It would be nice to handle the exception. Possibly like this: try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { handshakeFuture.setFailure(e); } I'm quite new to Netty so I don't know there is a better way. Does the modification make sense to you? ### Netty version 4.1.13 Regards, Martin
[ "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java" ]
[ "example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java" ]
[]
diff --git a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java index c36283cd8ef..fb10576e2e4 100644 --- a/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java +++ b/example/src/main/java/io/netty/example/http/websocketx/client/WebSocketClientHandler.java @@ -48,6 +48,7 @@ import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException; import io.netty.util.CharsetUtil; public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> { @@ -82,9 +83,14 @@ public void channelInactive(ChannelHandlerContext ctx) { public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { - handshaker.finishHandshake(ch, (FullHttpResponse) msg); - System.out.println("WebSocket Client connected!"); - handshakeFuture.setSuccess(); + try { + handshaker.finishHandshake(ch, (FullHttpResponse) msg); + System.out.println("WebSocket Client connected!"); + handshakeFuture.setSuccess(); + } catch (WebSocketHandshakeException e) { + System.out.println("WebSocket Client failed to connect"); + handshakeFuture.setFailure(e); + } return; }
null
test
train
"2017-07-20T10:24:18"
"2017-07-20T08:58:14Z"
MartyIX
val
netty/netty/7012_7013
netty/netty
netty/netty/7012
netty/netty/7013
[ "timestamp(timedelta=9.0, similarity=0.9377339943090868)" ]
452fd3624081553ed0d2b9b6f59c21789a274f69
b29f0a1023f4829c5899ed667c1424534c8f9b0a
[]
[]
"2017-07-23T14:22:29Z"
[]
small Default max message size in MqttDecoder
### Expected behavior According to [MQTT 3.1.1 spec, section 2.2.3](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html#_Toc385349759), MQTT packets size can take up to 268 435 455 bytes. I think this value should be a default. ### Actual behavior The current default value of MQTT packet to decode is 8092.
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java" ]
[ "codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java" ]
[]
diff --git a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java index 8d94ee48e96..6789722a895 100644 --- a/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java +++ b/codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttDecoder.java @@ -39,7 +39,7 @@ */ public final class MqttDecoder extends ReplayingDecoder<DecoderState> { - private static final int DEFAULT_MAX_BYTES_IN_MESSAGE = 8092; + private static final int DEFAULT_MAX_BYTES_IN_MESSAGE = 268435455; /** * States of the decoder.
null
train
train
"2017-07-22T17:44:48"
"2017-07-23T14:19:12Z"
Sammers21
val
netty/netty/7025_7026
netty/netty
netty/netty/7025
netty/netty/7026
[ "timestamp(timedelta=6.0, similarity=0.9000798950654655)" ]
efb2d141c1de9ef19443bb04678ef753894fcbe2
94b0b92f8d1f9a7214e12ac94458e7738ca25da8
[ "Check enable or not logger before encode already was introduced in #3492 but then lost in #6877", "Will fix ...", "@normanmaurer sorry, I already prepare PR #7026", "Ha! Even better\n\n> Am 26.07.2017 um 15:02 schrieb Vladimir Gordiychuk <notifications@github.com>:\n> \n> @normanmaurer sorry, I already prepare PR #7026\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Fixed by https://github.com/netty/netty/pull/7026." ]
[ "The log level will be enforced by the logger. We should only have to \"double check\" the log level if creation of one of the arguments may potentially be expensive. We should only need this double check on methods with a `toString(..)` as a parameter.\r\n\r\nAlternatively we could isolate the check in `toString`:\r\n\r\n```java\r\nprivate String toString(ByteBuf buf) {\r\n if (!logger.isEnabled(level)) {\r\n return \"\";\r\n }\r\n if (level == InternalLogLevel.TRACE || buf.readableBytes() <= BUFFER_LENGTH_THRESHOLD) {\r\n // Log the entire buffer.\r\n return ByteBufUtil.hexDump(buf);\r\n }\r\n\r\n // Otherwise just log the first 64 bytes.\r\n int length = Math.min(buf.readableBytes(), BUFFER_LENGTH_THRESHOLD);\r\n return ByteBufUtil.hexDump(buf, buf.readerIndex(), length) + \"...\";\r\n }\r\n```", "@Gordiychuk please address and once done we can merge it :)", "just one last nit: `StringUtil.EMPTY`" ]
"2017-07-26T13:01:48Z"
[ "defect" ]
Http2FrameLogger to many char[] allocation when logger disabled
### Expected behavior No char[] allocation when logger disabled ### Actual behavior The logger always performing a hex dump of the ByteBufs regarless whether or not the log would take place. I faced with huge allocation during run grpc benchmarks ![screenshot from 2017-07-26 15 40 17](https://user-images.githubusercontent.com/10699594/28621281-17ec8cfa-7219-11e7-8579-d51b7489072d.png) ### Netty version io.netty:netty-codec-http2:4.1.13.Final ### JVM version (e.g. `java -version`) java version "1.8.0_131" Java(TM) SE Runtime Environment (build 1.8.0_131-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java" ]
[]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java index 5a29d7f4616..f0297f9b1e9 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameLogger.java @@ -20,6 +20,7 @@ import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.logging.LogLevel; +import io.netty.util.internal.StringUtil; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogLevel; import io.netty.util.internal.logging.InternalLogger; @@ -132,6 +133,10 @@ public void logUnknownFrame(Direction direction, ChannelHandlerContext ctx, byte } private String toString(ByteBuf buf) { + if (!logger.isEnabled(level)) { + return StringUtil.EMPTY_STRING; + } + if (level == InternalLogLevel.TRACE || buf.readableBytes() <= BUFFER_LENGTH_THRESHOLD) { // Log the entire buffer. return ByteBufUtil.hexDump(buf);
null
train
train
"2017-07-25T16:18:52"
"2017-07-26T12:48:18Z"
Gordiychuk
val
netty/netty/3756_7058
netty/netty
netty/netty/3756
netty/netty/7058
[ "timestamp(timedelta=48.0, similarity=0.9515524125474241)" ]
348745608faae89c33d5dbae40be8e81b239177d
9408a6c203d5afa2512dfd839b8a1d2f6bb6e9f6
[ "Fixed by https://github.com/netty/netty/pull/7058" ]
[ "is this change necessary?", "would it make sense to move the OS X platform detection to `PlatformDependent`?", "yes as we use it in ´NativeLibraryLoader´", "sure we can do but as there were no other places where this is used I did not bother. ", "It looks like you removed all usages in this PR, or am I missing something?", "Yip understood. My rational is if we need todo macOS specific stuff in the future `PlatformDependent` is the natural place to look, but we may miss it (and duplicate it) if the logic lives in this class. Since `PlatformDependent` is internal and duplication removal was the motivation for this PR it seemed like it warranted a discussion.", "if that is true... which may be true that at the end I was able to remove all of them you are right... let me check", "true, let me move it.", "ok you are right... thanks :)" ]
"2017-08-06T14:07:25Z"
[ "cleanup" ]
Duplicate code in NativeLibraryLoader
`NativeLibraryLoader` has some functions which are similar to `PlatformDependent`'s. For example, - tmpdir() - toDirectory() - isWindow() I wonder if these can be replaced with functions of `PlatformDependent`. WDYT?
[ "common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java", "common/src/main/java/io/netty/util/internal/PlatformDependent.java" ]
[ "common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java", "common/src/main/java/io/netty/util/internal/PlatformDependent.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java index da8054a560c..729373506a6 100644 --- a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java +++ b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java @@ -31,7 +31,6 @@ import java.security.PrivilegedAction; import java.util.Arrays; import java.util.EnumSet; -import java.util.Locale; import java.util.Set; /** @@ -43,13 +42,10 @@ public final class NativeLibraryLoader { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class); private static final String NATIVE_RESOURCE_HOME = "META-INF/native/"; - private static final String OSNAME; private static final File WORKDIR; private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING; static { - OSNAME = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", ""); - String workdir = SystemPropertyUtil.get("io.netty.native.workdir"); if (workdir != null) { File f = new File(workdir); @@ -64,7 +60,7 @@ public final class NativeLibraryLoader { WORKDIR = f; logger.debug("-Dio.netty.native.workdir: " + WORKDIR); } else { - WORKDIR = tmpdir(); + WORKDIR = PlatformDependent.tmpdir(); logger.debug("-Dio.netty.native.workdir: " + WORKDIR + " (io.netty.tmpdir)"); } @@ -72,93 +68,6 @@ public final class NativeLibraryLoader { "io.netty.native.deleteLibAfterLoading", true); } - private static File tmpdir() { - File f; - try { - f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir")); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f); - return f; - } - - f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir")); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f + " (java.io.tmpdir)"); - return f; - } - - // This shouldn't happen, but just in case .. - if (isWindows()) { - f = toDirectory(System.getenv("TEMP")); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f + " (%TEMP%)"); - return f; - } - - String userprofile = System.getenv("USERPROFILE"); - if (userprofile != null) { - f = toDirectory(userprofile + "\\AppData\\Local\\Temp"); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f + " (%USERPROFILE%\\AppData\\Local\\Temp)"); - return f; - } - - f = toDirectory(userprofile + "\\Local Settings\\Temp"); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f + " (%USERPROFILE%\\Local Settings\\Temp)"); - return f; - } - } - } else { - f = toDirectory(System.getenv("TMPDIR")); - if (f != null) { - logger.debug("-Dio.netty.tmpdir: " + f + " ($TMPDIR)"); - return f; - } - } - } catch (Exception ignored) { - // Environment variable inaccessible - } - - // Last resort. - if (isWindows()) { - f = new File("C:\\Windows\\Temp"); - } else { - f = new File("/tmp"); - } - - logger.warn("Failed to get the temporary directory; falling back to: " + f); - return f; - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - private static File toDirectory(String path) { - if (path == null) { - return null; - } - - File f = new File(path); - f.mkdirs(); - - if (!f.isDirectory()) { - return null; - } - - try { - return f.getAbsoluteFile(); - } catch (Exception ignored) { - return f; - } - } - - private static boolean isWindows() { - return OSNAME.startsWith("windows"); - } - - private static boolean isOSX() { - return OSNAME.startsWith("macosx") || OSNAME.startsWith("osx"); - } - /** * Loads the first available library in the collection with the specified * {@link ClassLoader}. @@ -208,7 +117,7 @@ public static void load(String originalName, ClassLoader loader) { String path = NATIVE_RESOURCE_HOME + libname; URL url = loader.getResource(path); - if (url == null && isOSX()) { + if (url == null && PlatformDependent.isOsx()) { if (path.endsWith(".jnilib")) { url = loader.getResource(NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib"); } else { diff --git a/common/src/main/java/io/netty/util/internal/PlatformDependent.java b/common/src/main/java/io/netty/util/internal/PlatformDependent.java index e56ba5817cc..c97014edc5c 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -72,6 +72,8 @@ public final class PlatformDependent { "\\s*-XX:MaxDirectMemorySize\\s*=\\s*([0-9]+)\\s*([kKmMgG]?)\\s*$"); private static final boolean IS_WINDOWS = isWindows0(); + private static final boolean IS_OSX = isOsx0(); + private static final boolean MAYBE_SUPER_USER; private static final boolean CAN_ENABLE_TCP_NODELAY_BY_DEFAULT = !isAndroid(); @@ -207,6 +209,13 @@ public static boolean isWindows() { return IS_WINDOWS; } + /** + * Return {@code true} if the JVM is running on OSX / MacOS + */ + public static boolean isOsx() { + return IS_OSX; + } + /** * Return {@code true} if the current user may be a super-user. Be aware that this is just an hint and so it may * return false-positives. @@ -923,6 +932,16 @@ private static boolean isWindows0() { return windows; } + private static boolean isOsx0() { + String osname = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US); + boolean osx = osname.startsWith("macosx") || osname.startsWith("osx"); + + if (osx) { + logger.debug("Platform: MacOS"); + } + return osx; + } + private static boolean maybeSuperUser0() { String username = SystemPropertyUtil.get("user.name"); if (isWindows()) {
null
test
train
"2017-08-08T07:47:18"
"2015-05-07T09:37:46Z"
jlim262
val
netty/netty/6576_7099
netty/netty
netty/netty/6576
netty/netty/7099
[ "timestamp(timedelta=16.0, similarity=0.904038667647538)" ]
505993a2fb6016c58d0f95392d7317a6d80f2ac7
d543509085bd1d2132919bb0ca225177a2ff5b1f
[ "Probably not a good idea to add these methods to 4.1 but we could in 4.2+", "@trustin I guess we still could as `ByteBuf` is an abstract class and just implement them directly there. We then could implement these in an optimized way in the sub-classes. WDYT ?", "Sounds good to me as long as we put some noticeable note in the announcement. :-)", "@trustin want to take a crack on this or should I do ?", "Will find some time this week since this isn't an urgent one. :-)", "@trustin ok cool :)", "I came to a point in our game project where we need this and we cannot use it\r\n\r\n+1", "@martin3361 if you want to you could provide a pr for this. ", "@normanmaurer I'm not sure if I can since I'm not familiar with endianness and how to implement it", "Here is what I use for workaround:\r\n\r\n\tprivate void writeFloat(ByteBuf in, float value) {\r\n\t\tin.writeBytes(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putFloat(value).array());\r\n\t}", "Fixed by https://github.com/netty/netty/pull/7099", "I'm working on gps devices server and I really need this asap 🚜 \r\n\r\n+1" ]
[]
"2017-08-12T19:44:42Z"
[ "feature" ]
ByteBuf does not have access methods for little endian floats and doubles
### Expected behavior `ByteBuf` has `get/read/set/writeFloatLE()` and `get/read/set/writeDoubleLE()`. ### Actual behavior `ByteBuf` does not have the little endian variant of float/double access methods. ### Netty version 4.0.x and 4.1.x
[ "buffer/src/main/java/io/netty/buffer/ByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBuf.java b/buffer/src/main/java/io/netty/buffer/ByteBuf.java index 607a4b13acc..753c67a97a4 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBuf.java @@ -757,6 +757,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract float getFloat(int index); + /** + * Gets a 32-bit floating point number at the specified absolute + * {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public float getFloatLE(int index) { + return Float.intBitsToFloat(getIntLE(index)); + } + /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify @@ -768,6 +782,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract double getDouble(int index); + /** + * Gets a 64-bit floating point number at the specified absolute + * {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public double getDoubleLE(int index) { + return Double.longBitsToDouble(getLongLE(index)); + } + /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination becomes @@ -1089,6 +1117,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf setFloat(int index, float value); + /** + * Sets the specified 32-bit floating-point number at the specified + * absolute {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public ByteBuf setFloatLE(int index, float value) { + return setIntLE(index, Float.floatToRawIntBits(value)); + } + /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer. @@ -1101,6 +1143,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf setDouble(int index, double value); + /** + * Sets the specified 64-bit floating-point number at the specified + * absolute {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public ByteBuf setDoubleLE(int index, double value) { + return setLongLE(index, Double.doubleToRawLongBits(value)); + } + /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer becomes @@ -1463,6 +1519,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract float readFloat(); + /** + * Gets a 32-bit floating point number at the current {@code readerIndex} + * in Little Endian Byte Order and increases the {@code readerIndex} + * by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 4} + */ + public float readFloatLE() { + return Float.intBitsToFloat(readIntLE()); + } + /** * Gets a 64-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. @@ -1472,6 +1540,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract double readDouble(); + /** + * Gets a 64-bit floating point number at the current {@code readerIndex} + * in Little Endian Byte Order and increases the {@code readerIndex} + * by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 8} + */ + public double readDoubleLE() { + return Double.longBitsToDouble(readLongLE()); + } + /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} and increases the {@code readerIndex} @@ -1794,6 +1874,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf writeFloat(float value); + /** + * Sets the specified 32-bit floating point number at the current + * {@code writerIndex} in Little Endian Byte Order and increases + * the {@code writerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 4} + */ + public ByteBuf writeFloatLE(float value) { + return writeIntLE(Float.floatToRawIntBits(value)); + } + /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} @@ -1804,6 +1896,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf writeDouble(double value); + /** + * Sets the specified 64-bit floating point number at the current + * {@code writerIndex} in Little Endian Byte Order and increases + * the {@code writerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 8} + */ + public ByteBuf writeDoubleLE(double value) { + return writeLongLE(Double.doubleToRawLongBits(value)); + } + /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer becomes
diff --git a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java index ef2cd3c08d0..e4a117a2063 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java @@ -786,29 +786,57 @@ private void testLongConsistentWithByteBuffer(boolean direct, boolean testBigEnd @Test public void testRandomFloatAccess() { + testRandomFloatAccess(true); + } + + @Test + public void testRandomFloatLEAccess() { + testRandomFloatAccess(false); + } + + private void testRandomFloatAccess(boolean testBigEndian) { for (int i = 0; i < buffer.capacity() - 7; i += 8) { float value = random.nextFloat(); - buffer.setFloat(i, value); + if (testBigEndian) { + buffer.setFloat(i, value); + } else { + buffer.setFloatLE(i, value); + } } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 7; i += 8) { - float value = random.nextFloat(); - assertEquals(value, buffer.getFloat(i), 0.01); + float expected = random.nextFloat(); + float actual = testBigEndian? buffer.getFloat(i) : buffer.getFloatLE(i); + assertEquals(expected, actual, 0.01); } } @Test public void testRandomDoubleAccess() { + testRandomDoubleAccess(true); + } + + @Test + public void testRandomDoubleLEAccess() { + testRandomDoubleAccess(false); + } + + private void testRandomDoubleAccess(boolean testBigEndian) { for (int i = 0; i < buffer.capacity() - 7; i += 8) { double value = random.nextDouble(); - buffer.setDouble(i, value); + if (testBigEndian) { + buffer.setDouble(i, value); + } else { + buffer.setDoubleLE(i, value); + } } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 7; i += 8) { - double value = random.nextDouble(); - assertEquals(value, buffer.getDouble(i), 0.01); + double expected = random.nextDouble(); + double actual = testBigEndian? buffer.getDouble(i) : buffer.getDoubleLE(i); + assertEquals(expected, actual, 0.01); } } @@ -2615,11 +2643,21 @@ public void testGetFloatAfterRelease() { releasedBuffer().getFloat(0); } + @Test(expected = IllegalReferenceCountException.class) + public void testGetFloatLEAfterRelease() { + releasedBuffer().getFloatLE(0); + } + @Test(expected = IllegalReferenceCountException.class) public void testGetDoubleAfterRelease() { releasedBuffer().getDouble(0); } + @Test(expected = IllegalReferenceCountException.class) + public void testGetDoubleLEAfterRelease() { + releasedBuffer().getDoubleLE(0); + } + @Test(expected = IllegalReferenceCountException.class) public void testGetBytesAfterRelease() { ByteBuf buffer = buffer(8); @@ -2919,11 +2957,21 @@ public void testReadFloatAfterRelease() { releasedBuffer().readFloat(); } + @Test(expected = IllegalReferenceCountException.class) + public void testReadFloatLEAfterRelease() { + releasedBuffer().readFloatLE(); + } + @Test(expected = IllegalReferenceCountException.class) public void testReadDoubleAfterRelease() { releasedBuffer().readDouble(); } + @Test(expected = IllegalReferenceCountException.class) + public void testReadDoubleLEAfterRelease() { + releasedBuffer().readDoubleLE(); + } + @Test(expected = IllegalReferenceCountException.class) public void testReadBytesAfterRelease() { releasedBuffer().readBytes(1); @@ -3049,11 +3097,21 @@ public void testWriteFloatAfterRelease() { releasedBuffer().writeFloat(1); } + @Test(expected = IllegalReferenceCountException.class) + public void testWriteFloatLEAfterRelease() { + releasedBuffer().writeFloatLE(1); + } + @Test(expected = IllegalReferenceCountException.class) public void testWriteDoubleAfterRelease() { releasedBuffer().writeDouble(1); } + @Test(expected = IllegalReferenceCountException.class) + public void testWriteDoubleLEAfterRelease() { + releasedBuffer().writeDoubleLE(1); + } + @Test(expected = IllegalReferenceCountException.class) public void testWriteBytesAfterRelease() { ByteBuf buffer = buffer(8);
train
train
"2017-08-12T20:19:12"
"2017-03-28T08:17:29Z"
trustin
val
netty/netty/6127_7099
netty/netty
netty/netty/6127
netty/netty/7099
[ "timestamp(timedelta=6056.0, similarity=0.8735487342040955)" ]
505993a2fb6016c58d0f95392d7317a6d80f2ac7
d543509085bd1d2132919bb0ca225177a2ff5b1f
[ "Although this wouldn't be consistent with `readDouble` and `readFloat` (which are abstract and implemented in `AbstractByteBuf`) we could add these methods and default implementations to `ByteBuf` ... @normanmaurer WDYT?", "@Scottmitch yeah... not sure about it... Let me think about it :)", "This was fixed by https://github.com/netty/netty/pull/7099" ]
[]
"2017-08-12T19:44:42Z"
[]
Add readDoubleLE and readFloatLE methods to ByteBuf
ByteBuf.order methods are deprecated now and getShortLE, getIntLE .. methods should be used instead. But such important methods like `readDoubleLE` and `readFloatLE` are not implemented. ### Netty version Netty 4.1.6
[ "buffer/src/main/java/io/netty/buffer/ByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBuf.java b/buffer/src/main/java/io/netty/buffer/ByteBuf.java index 607a4b13acc..753c67a97a4 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBuf.java @@ -757,6 +757,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract float getFloat(int index); + /** + * Gets a 32-bit floating point number at the specified absolute + * {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public float getFloatLE(int index) { + return Float.intBitsToFloat(getIntLE(index)); + } + /** * Gets a 64-bit floating point number at the specified absolute * {@code index} in this buffer. This method does not modify @@ -768,6 +782,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract double getDouble(int index); + /** + * Gets a 64-bit floating point number at the specified absolute + * {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public double getDoubleLE(int index) { + return Double.longBitsToDouble(getLongLE(index)); + } + /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination becomes @@ -1089,6 +1117,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf setFloat(int index, float value); + /** + * Sets the specified 32-bit floating-point number at the specified + * absolute {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public ByteBuf setFloatLE(int index, float value) { + return setIntLE(index, Float.floatToRawIntBits(value)); + } + /** * Sets the specified 64-bit floating-point number at the specified * absolute {@code index} in this buffer. @@ -1101,6 +1143,20 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf setDouble(int index, double value); + /** + * Sets the specified 64-bit floating-point number at the specified + * absolute {@code index} in this buffer in Little Endian Byte Order. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public ByteBuf setDoubleLE(int index, double value) { + return setLongLE(index, Double.doubleToRawLongBits(value)); + } + /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer becomes @@ -1463,6 +1519,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract float readFloat(); + /** + * Gets a 32-bit floating point number at the current {@code readerIndex} + * in Little Endian Byte Order and increases the {@code readerIndex} + * by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 4} + */ + public float readFloatLE() { + return Float.intBitsToFloat(readIntLE()); + } + /** * Gets a 64-bit floating point number at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. @@ -1472,6 +1540,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract double readDouble(); + /** + * Gets a 64-bit floating point number at the current {@code readerIndex} + * in Little Endian Byte Order and increases the {@code readerIndex} + * by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 8} + */ + public double readDoubleLE() { + return Double.longBitsToDouble(readLongLE()); + } + /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} and increases the {@code readerIndex} @@ -1794,6 +1874,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf writeFloat(float value); + /** + * Sets the specified 32-bit floating point number at the current + * {@code writerIndex} in Little Endian Byte Order and increases + * the {@code writerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 4} + */ + public ByteBuf writeFloatLE(float value) { + return writeIntLE(Float.floatToRawIntBits(value)); + } + /** * Sets the specified 64-bit floating point number at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} @@ -1804,6 +1896,18 @@ public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> { */ public abstract ByteBuf writeDouble(double value); + /** + * Sets the specified 64-bit floating point number at the current + * {@code writerIndex} in Little Endian Byte Order and increases + * the {@code writerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 8} + */ + public ByteBuf writeDoubleLE(double value) { + return writeLongLE(Double.doubleToRawLongBits(value)); + } + /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer becomes
diff --git a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java index ef2cd3c08d0..e4a117a2063 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractByteBufTest.java @@ -786,29 +786,57 @@ private void testLongConsistentWithByteBuffer(boolean direct, boolean testBigEnd @Test public void testRandomFloatAccess() { + testRandomFloatAccess(true); + } + + @Test + public void testRandomFloatLEAccess() { + testRandomFloatAccess(false); + } + + private void testRandomFloatAccess(boolean testBigEndian) { for (int i = 0; i < buffer.capacity() - 7; i += 8) { float value = random.nextFloat(); - buffer.setFloat(i, value); + if (testBigEndian) { + buffer.setFloat(i, value); + } else { + buffer.setFloatLE(i, value); + } } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 7; i += 8) { - float value = random.nextFloat(); - assertEquals(value, buffer.getFloat(i), 0.01); + float expected = random.nextFloat(); + float actual = testBigEndian? buffer.getFloat(i) : buffer.getFloatLE(i); + assertEquals(expected, actual, 0.01); } } @Test public void testRandomDoubleAccess() { + testRandomDoubleAccess(true); + } + + @Test + public void testRandomDoubleLEAccess() { + testRandomDoubleAccess(false); + } + + private void testRandomDoubleAccess(boolean testBigEndian) { for (int i = 0; i < buffer.capacity() - 7; i += 8) { double value = random.nextDouble(); - buffer.setDouble(i, value); + if (testBigEndian) { + buffer.setDouble(i, value); + } else { + buffer.setDoubleLE(i, value); + } } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 7; i += 8) { - double value = random.nextDouble(); - assertEquals(value, buffer.getDouble(i), 0.01); + double expected = random.nextDouble(); + double actual = testBigEndian? buffer.getDouble(i) : buffer.getDoubleLE(i); + assertEquals(expected, actual, 0.01); } } @@ -2615,11 +2643,21 @@ public void testGetFloatAfterRelease() { releasedBuffer().getFloat(0); } + @Test(expected = IllegalReferenceCountException.class) + public void testGetFloatLEAfterRelease() { + releasedBuffer().getFloatLE(0); + } + @Test(expected = IllegalReferenceCountException.class) public void testGetDoubleAfterRelease() { releasedBuffer().getDouble(0); } + @Test(expected = IllegalReferenceCountException.class) + public void testGetDoubleLEAfterRelease() { + releasedBuffer().getDoubleLE(0); + } + @Test(expected = IllegalReferenceCountException.class) public void testGetBytesAfterRelease() { ByteBuf buffer = buffer(8); @@ -2919,11 +2957,21 @@ public void testReadFloatAfterRelease() { releasedBuffer().readFloat(); } + @Test(expected = IllegalReferenceCountException.class) + public void testReadFloatLEAfterRelease() { + releasedBuffer().readFloatLE(); + } + @Test(expected = IllegalReferenceCountException.class) public void testReadDoubleAfterRelease() { releasedBuffer().readDouble(); } + @Test(expected = IllegalReferenceCountException.class) + public void testReadDoubleLEAfterRelease() { + releasedBuffer().readDoubleLE(); + } + @Test(expected = IllegalReferenceCountException.class) public void testReadBytesAfterRelease() { releasedBuffer().readBytes(1); @@ -3049,11 +3097,21 @@ public void testWriteFloatAfterRelease() { releasedBuffer().writeFloat(1); } + @Test(expected = IllegalReferenceCountException.class) + public void testWriteFloatLEAfterRelease() { + releasedBuffer().writeFloatLE(1); + } + @Test(expected = IllegalReferenceCountException.class) public void testWriteDoubleAfterRelease() { releasedBuffer().writeDouble(1); } + @Test(expected = IllegalReferenceCountException.class) + public void testWriteDoubleLEAfterRelease() { + releasedBuffer().writeDoubleLE(1); + } + @Test(expected = IllegalReferenceCountException.class) public void testWriteBytesAfterRelease() { ByteBuf buffer = buffer(8);
train
train
"2017-08-12T20:19:12"
"2016-12-12T10:39:37Z"
mrniko
val
netty/netty/6933_7126
netty/netty
netty/netty/6933
netty/netty/7126
[ "timestamp(timedelta=677.0, similarity=0.9227435941944693)" ]
c93e58c453147ab5b34a708a85530d2372bbac81
d5b78a09004f35d8732a0ce1d1e33a2e8cad41df
[ "I forgot the most obvious solution, which is to create a `java.lang.reflect.Proxy` from a simple `InvocationHandler` that delegates to `ProtocolSelector#select`. This is much simpler than defining a class directly from an ASM-produced `byte[]`, but I don't know what the performance implications are.", "@rschmitt not yet and it may take some time before I have cycles to spend here. ", "@rschmitt maybe you could create a POC with a JMH benchmark?", "@johnou Actually, I think I see a way to go through the `MethodHandle` API instead, which should combine the performance of the ASM approach with the encapsulation properties of the Proxy approach. (The ASM approach requires a `setAccessible(true)` call so that `defineClass` can be invoked.)", "Actually, the ASM approach could work nicely on Java 9 via this public method: http://download.java.net/java/jdk9/docs/api/java/lang/invoke/MethodHandles.Lookup.html#defineClass-byte:A-", "Fixed by https://github.com/netty/netty/pull/7126", "@normanmaurer did you by chance run the benchmarks to compare Java 9 ALPN to the other engines? ", "@johnou nope... that said I expect it to be slow still as SSL perf in JDK is still a way worse compared to netty-tcnative or conscrypt.", "Hi, I have JDK 9 and took the latest sample from the developer blog. Still I get a Connection Timed Out error. Do I have to update anything ?" ]
[ "Do we care about double spaces? ", "And server mode? Throw unsupported operation exception? ", "Does this need to be invoked every setHandshakeSuccess? ", "Yes need to fix", "This way I not need any checks in SslHandler....", "I guess it would be better to only call it once... let me fix", "actually this is good as it is ", "ObjectUtil.checkNotNull ?", "nit: check that the args are the correct count and type?", "should this be logged?", "optional, but I would put jdk ahead of alpn. ", "yep thats a good idea I think... at least with an assert...", "maybe... I am not sure.. @Scottmitch ?", "sure why not...", "not needed as we instance if only internally and we know it can't be null.", "as we cast arg[1] below I not added another assert here.", "You might consider renaming selectProtocol to clientSelectProtocol, or selectProtocolIfClient or something like.", "`selectProtocolIfClient` sounds good.", "Include what the name was? i.e. \r\n\r\n`assert \"apply\".equals(method.getName()); : \"unexpected method \" + method.getName();`", "same comment as above.", "out of curiosity, what exception do you expect here that you want to ignore?", "in regard to the above, can you move this above the `if (JettyAlpnSslEngine.isAvailable()) {` ? Jetty is a horrible hack and should be avoided if possible.", "We actually throw an exception if we want it to fail for example:\r\n\r\nhttps://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java#L205", "+1", "What's the point of this? In normal usage `setApplicationProtocols` method won't throw; `SSLParameters` is independent of the provider/engine implementation.", "Not a show-stopper, but...\r\n\r\nThis makes me a bit uncomfortable, because it is assuming quite a few things are working in concert[1]. For instance, this won't behave correctly if the default provider doesn't match the default SSLContext. That could be fixed by using `SSLContext.getInstance(\"TLS\")` here instead. But it also doesn't work when explicitly providing a sslContextProvider.\r\n\r\nThe only part of this logic that is provider-specific is the `getter.invoke(engine);`. In `JdkSslContext`, could we pass the `sslContextProvider` to `JdkAlpnApplicationProtocolNegotiator`'s constructor, and plumb it into the decision-making? That would mean we would create a throw-away `SSLContext` and `SSLEngine` once per Netty-`SslContext` creation, though.\r\n\r\nTechnically, right now the provider can be different each `SSLContext/SSLEngine`, since the provider isn't fully-chosen until `JdkSslClientContext.newSSLContext()`. If `sslContextProvider == null`, it uses the default at the time of the call via `SSLContext.getInstance(PROTOCOL)`. It may be a good idea to \"choose\" the provider earlier, like in the constructor via `Security.getProvider(\"SSLContext.\" + PROTOCOL)`.\r\n\r\n1. This was fairly unavoidable with Jetty ALPN, but seems avoidable (if still a PITA) with JDK 9-provided ALPN.", "the point was to try to use the method via reflection to ensure nothing will blow-up on runtime ", "@ejona86 the idea of this method was just to ensure all the reflective calls will work before we try to use these at runtime. I think if we change this to `SSLContext.getInstance(\"TLS\")` this should be good enough, no ? ", "@ejona86 actually I think I understand now what you are suggesting. Let me try this...", "@ejona86 after thinking a bt more about it and hacking on it I think we should just use `SSLContext.getInstance(\"TLS\")` for now and be happy. The problem is that we still have constructors that take `JdkApplicationProtocolNegotiator` and so its hard to to make this work without any hacks. That said I deprecated these in another PR:\r\n\r\nhttps://github.com/netty/netty/pull/7138", "Oh, okay. FYI: setHandshakeApplicationProtocolSelector isn't tried here. That doesn't really bother me, though.", "Hmm... that is even more troublesome. Yeah, swapping to `SSLContext.getInstance(\"TLS\")` is enough at this point.", "nit: this is not necessary as it it is used in `configureAlpn` before this method is called.", "> If the return value is null (no value chosen) or is a value that was not advertised by the peer, the underlying protocol will determine what action to take.\r\n\r\nReturning `null` allows the underlying layers to determine what todo. If the implementation strictly follows the RFC it should fail the handshake with a no_application_protocol [1]. However some TLS implementations (e.g. OpenSSL) have not implemented support for this alert until recently and would no advertise support for ALPN instead of failing the handshake. Throwing a `SSLHandshakeException` ensured that we failed the handshake (maybe not with the correct alert because it wasn't exposed at the time). That is the purpose of `SelectorFailureBehavior` and `SelectedListenerFailureBehavior` to allow us to have control over this at the application level since lower levels allowed us more freedom.\r\n\r\n[1] https://tools.ietf.org/rfc/rfc7301.txt", "nit: kill newline?", "should we try to use http://download.java.net/java/jdk9/docs/api/javax/net/ssl/SSLEngine.html#getApplicationProtocol-- here?", "discussed with @normanmaurer offline. This may lead to treating the SslSession object differently in JDK9 and lower ... can we avoid this?", "If `Java9SslUtils.getApplicationProtocol(getWrappedEngine())` returns `null` (and maybe empty) (assuming the handshake is done) shouldn't we call [ProtocolSelectionListener#unsupported](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/JdkApplicationProtocolNegotiator.java#L104)?\r\n\r\nhttp://download.java.net/java/jdk9/docs/api/javax/net/ssl/SSLEngine.html#getApplicationProtocol--\r\n> Returns:\r\nnull if it has not yet been determined if application protocols might be used for this connection, an empty String if application protocols values will not be used, or a non-empty application protocol String if a value was successfully negotiated.", "under what conditions can we invoke `ProtocolSelector#unsupported()`? Will this callback be called if the peer doesn't advertise ALPN, and if so what will the arguments be? Consider adding a comment.", "+1", "![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) The Cyclomatic Complexity of this class is 520 which is greater than 300 authorized. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=squid%3AClassCyclomaticComplexity)\n", "nit: kill extra line", "nit: `log` -> `logger` for consistency?", "can we do this outside the scope of the constructor to avoid allowing `this` to escape? maybe in `wrapEngine` or create a static factory method in here?", "nit: consider adding a static import for `ProtocolSelector` to help with formatting.", "nit: consider adding a static import for `ProtocolSelectionListener` to help with formatting.", "https://github.com/netty/netty/pull/7126#discussion_r134666394\r\n\r\n> under what conditions can we invoke `ProtocolSelector#unsupported()`? Will this BiFunction be called if the peer doesn't advertise ALPN, and if so what will the arguments be? Consider adding a comment.", "nit: consider reformatting:\r\n\r\n```java\r\n private static final boolean AVAILABLE = Conscrypt.isAvailable() ||\r\n jdkAlpnSupported() ||\r\n JettyAlpnSslEngine.isAvailable();\r\n```", "can `applicationProtocol` be volatile instead of requiring synchronization?", "it would be nice not to have to call this on every wrap/unwrap. It looks like this is not necessary on the server. Is it worth having a `Java9ServerSslEngine` and `Java9ClientSslEngine` ... and the `Java9ServerSslEngine` wouldn't have todo this at all? `Java9ClientSslEngine ` wouldn't need to have `setHandshakeApplicationProtocolSelector` or `getHandshakeApplicationProtocolSelector` either.", "Good idea", "I can do this that said we still need the set and get as this must delegate to the wrapped engine to be able to delegate all methods of the java9 SSLEngine ", "Yep I think this should be fine ", "Let me find out...", "after thinking more about this I think it is fine to just keep one implementation and just reverse the checks as the JIT should be smart enough to know it will never match when the engine is server side. if it really shows up to be an issue we can do a followup.", "done", "> as the JIT should be smart enough to know it will never match when the engine is server side.\r\n\r\nThis would be an interesting optimization ... conditional code elimination based upon the usage of the class. Are you assuming the JIT would effectively? create the two different classes behind the scenes?", "basically I think the JIT should figure out that a boolean will always match or not match and if not just optimise the branch away ;)\r\n\r\nThat said after addressing your comment I need extra code for server and client side anyway.", "this call can be moved into the conditional below", "nit: fix argument alignment", "nit: fix argument alignment", "![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Consider using varargs for methods or constructors which take an array the last parameter. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=pmd%3AUseVarargs)\n" ]
"2017-08-18T11:53:53Z"
[ "feature" ]
Netty 4.1 should support ALPN on JDK9
This is obviously a known issue, but it's worth tracking. It may also be tricky to pull this off while compiling against JDK6; in particular, invoking `SSLEngine#setHandshakeApplicationProtocolSelector` requires passing a `BiFunction` implementation. I see a few ways of accomplishing this, assuming that calling this method turns out to be necessary: 1. Take advantage of [JEP 238](http://openjdk.java.net/jeps/238) (Multi-Release JAR Files) to compile and link a small amount of code directly against JDK9 2. Use reflection to call `java.lang.invoke.MethodHandleProxies#asInterfaceInstance` 3. Use a library like ASM to manually generate a `BiFunction` implementation at runtime
[ "handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java", "handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java", "handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/JdkSslSession.java", "handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "pom.xml" ]
[ "handler/src/main/java/io/netty/handler/ssl/Java9SslEngine.java", "handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java", "handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java", "handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java", "handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "pom.xml" ]
[ "handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/Java9SslEngine.java b/handler/src/main/java/io/netty/handler/ssl/Java9SslEngine.java new file mode 100644 index 00000000000..6534f39b503 --- /dev/null +++ b/handler/src/main/java/io/netty/handler/ssl/Java9SslEngine.java @@ -0,0 +1,175 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.ssl; + +import io.netty.util.internal.StringUtil; + +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLException; + +import java.nio.ByteBuffer; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.function.BiFunction; + +import static io.netty.handler.ssl.SslUtils.toSSLHandshakeException; +import static io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelectionListener; +import static io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelector; + +final class Java9SslEngine extends JdkSslEngine { + private final ProtocolSelectionListener selectionListener; + private final AlpnSelector alpnSelector; + + private final class AlpnSelector implements BiFunction<SSLEngine, List<String>, String> { + private final ProtocolSelector selector; + private boolean called; + + AlpnSelector(ProtocolSelector selector) { + this.selector = selector; + } + + @Override + public String apply(SSLEngine sslEngine, List<String> strings) { + assert !called; + called = true; + + try { + String selected = selector.select(strings); + return selected == null ? StringUtil.EMPTY_STRING : selected; + } catch (Exception cause) { + // Returning null means we want to fail the handshake. + // + // See http://download.java.net/java/jdk9/docs/api/javax/net/ssl/ + // SSLEngine.html#setHandshakeApplicationProtocolSelector-java.util.function.BiFunction- + return null; + } + } + + void checkUnsupported() { + if (called) { + // ALPN message was received by peer and so apply(...) was called. + // See: + // http://hg.openjdk.java.net/jdk9/dev/jdk/file/65464a307408/src/ + // java.base/share/classes/sun/security/ssl/ServerHandshaker.java#l933 + return; + } + String protocol = getApplicationProtocol(); + assert protocol != null; + + if (protocol.isEmpty()) { + // ALPN is not supported + selector.unsupported(); + } + } + } + + Java9SslEngine(SSLEngine engine, JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) { + super(engine); + if (isServer) { + selectionListener = null; + alpnSelector = new AlpnSelector(applicationNegotiator.protocolSelectorFactory(). + newSelector(this, new LinkedHashSet<String>(applicationNegotiator.protocols()))); + Java9SslUtils.setHandshakeApplicationProtocolSelector(engine, alpnSelector); + } else { + selectionListener = applicationNegotiator.protocolListenerFactory() + .newListener(this, applicationNegotiator.protocols()); + alpnSelector = null; + Java9SslUtils.setApplicationProtocols(engine, applicationNegotiator.protocols()); + } + } + + private SSLEngineResult verifyProtocolSelection(SSLEngineResult result) throws SSLException { + if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED) { + if (alpnSelector == null) { + // This means we are using client-side and + try { + String protocol = getApplicationProtocol(); + assert protocol != null; + if (protocol.isEmpty()) { + // If empty the server did not announce ALPN: + // See: + // http://hg.openjdk.java.net/jdk9/dev/jdk/file/65464a307408/src/java.base/ + // share/classes/sun/security/ssl/ClientHandshaker.java#l741 + selectionListener.unsupported(); + } else { + selectionListener.selected(protocol); + } + } catch (Throwable e) { + throw toSSLHandshakeException(e); + } + } else { + assert selectionListener == null; + alpnSelector.checkUnsupported(); + } + } + return result; + } + + @Override + public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException { + return verifyProtocolSelection(super.wrap(src, dst)); + } + + @Override + public SSLEngineResult wrap(ByteBuffer[] srcs, ByteBuffer dst) throws SSLException { + return verifyProtocolSelection(super.wrap(srcs, dst)); + } + + @Override + public SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int len, ByteBuffer dst) throws SSLException { + return verifyProtocolSelection(super.wrap(srcs, offset, len, dst)); + } + + @Override + public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException { + return verifyProtocolSelection(super.unwrap(src, dst)); + } + + @Override + public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException { + return verifyProtocolSelection(super.unwrap(src, dsts)); + } + + @Override + public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dst, int offset, int len) throws SSLException { + return verifyProtocolSelection(super.unwrap(src, dst, offset, len)); + } + + @Override + void setApplicationProtocol(String applicationProtocol) { + // Do nothing as this is handled internally by the Java9 implementation of SSLEngine. + } + + @Override + public String getApplicationProtocol() { + return Java9SslUtils.getApplicationProtocol(getWrappedEngine()); + } + + // These methods will override the methods defined by Java 9. As we compile with Java8 we can not add + // @Override annotations here. + public String getHandshakeApplicationProtocol() { + return Java9SslUtils.getHandshakeApplicationProtocol(getWrappedEngine()); + } + + public void setHandshakeApplicationProtocolSelector(BiFunction<SSLEngine, List<String>, String> selector) { + Java9SslUtils.setHandshakeApplicationProtocolSelector(getWrappedEngine(), selector); + } + + public BiFunction<SSLEngine, List<String>, String> getHandshakeApplicationProtocolSelector() { + return Java9SslUtils.getHandshakeApplicationProtocolSelector(getWrappedEngine()); + } +} diff --git a/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java b/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java new file mode 100644 index 00000000000..2fd3bbcd64b --- /dev/null +++ b/handler/src/main/java/io/netty/handler/ssl/Java9SslUtils.java @@ -0,0 +1,175 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.ssl; + + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLParameters; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedExceptionAction; +import java.util.List; +import java.util.function.BiFunction; + +import io.netty.util.internal.EmptyArrays; +import io.netty.util.internal.PlatformDependent; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; + +final class Java9SslUtils { + private static final InternalLogger logger = InternalLoggerFactory.getInstance(Java9SslUtils.class); + private static final Method SET_APPLICATION_PROTOCOLS; + private static final Method GET_APPLICATION_PROTOCOL; + private static final Method GET_HANDSHAKE_APPLICATION_PROTOCOL; + private static final Method SET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR; + private static final Method GET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR; + + static { + Method getHandshakeApplicationProtocol = null; + Method getApplicationProtocol = null; + Method setApplicationProtocols = null; + Method setHandshakeApplicationProtocolSelector = null; + Method getHandshakeApplicationProtocolSelector = null; + + try { + SSLContext context = SSLContext.getInstance(JdkSslContext.PROTOCOL); + context.init(null, null, null); + SSLEngine engine = context.createSSLEngine(); + getHandshakeApplicationProtocol = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { + @Override + public Method run() throws Exception { + return SSLEngine.class.getMethod("getHandshakeApplicationProtocol"); + } + }); + getHandshakeApplicationProtocol.invoke(engine); + getApplicationProtocol = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { + @Override + public Method run() throws Exception { + return SSLEngine.class.getMethod("getApplicationProtocol"); + } + }); + getApplicationProtocol.invoke(engine); + + setApplicationProtocols = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { + @Override + public Method run() throws Exception { + return SSLParameters.class.getMethod("setApplicationProtocols", String[].class); + } + }); + setApplicationProtocols.invoke(engine.getSSLParameters(), new Object[]{EmptyArrays.EMPTY_STRINGS}); + + setHandshakeApplicationProtocolSelector = + AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { + @Override + public Method run() throws Exception { + return SSLEngine.class.getMethod("setHandshakeApplicationProtocolSelector", BiFunction.class); + } + }); + setHandshakeApplicationProtocolSelector.invoke(engine, new BiFunction<SSLEngine, List<String>, String>() { + @Override + public String apply(SSLEngine sslEngine, List<String> strings) { + return null; + } + }); + + getHandshakeApplicationProtocolSelector = + AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { + @Override + public Method run() throws Exception { + return SSLEngine.class.getMethod("getHandshakeApplicationProtocolSelector"); + } + }); + getHandshakeApplicationProtocolSelector.invoke(engine); + } catch (Throwable t) { + logger.error("Unable to initialize Java9SslUtils, but the detected javaVersion was: {}", + PlatformDependent.javaVersion(), t); + getHandshakeApplicationProtocol = null; + getApplicationProtocol = null; + setApplicationProtocols = null; + setHandshakeApplicationProtocolSelector = null; + getHandshakeApplicationProtocolSelector = null; + } + GET_HANDSHAKE_APPLICATION_PROTOCOL = getHandshakeApplicationProtocol; + GET_APPLICATION_PROTOCOL = getApplicationProtocol; + SET_APPLICATION_PROTOCOLS = setApplicationProtocols; + SET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR = setHandshakeApplicationProtocolSelector; + GET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR = getHandshakeApplicationProtocolSelector; + } + + private Java9SslUtils() { + } + + static boolean supportsAlpn() { + return GET_APPLICATION_PROTOCOL != null; + } + + static String getApplicationProtocol(SSLEngine sslEngine) { + try { + return (String) GET_APPLICATION_PROTOCOL.invoke(sslEngine); + } catch (UnsupportedOperationException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + static String getHandshakeApplicationProtocol(SSLEngine sslEngine) { + try { + return (String) GET_HANDSHAKE_APPLICATION_PROTOCOL.invoke(sslEngine); + } catch (UnsupportedOperationException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + static void setApplicationProtocols(SSLEngine engine, List<String> supportedProtocols) { + SSLParameters parameters = engine.getSSLParameters(); + + String[] protocolArray = supportedProtocols.toArray(EmptyArrays.EMPTY_STRINGS); + try { + SET_APPLICATION_PROTOCOLS.invoke(parameters, new Object[]{protocolArray}); + } catch (UnsupportedOperationException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + engine.setSSLParameters(parameters); + } + + static void setHandshakeApplicationProtocolSelector( + SSLEngine engine, BiFunction<SSLEngine, List<String>, String> selector) { + try { + SET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR.invoke(engine, selector); + } catch (UnsupportedOperationException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + static BiFunction<SSLEngine, List<String>, String> getHandshakeApplicationProtocolSelector(SSLEngine engine) { + try { + return (BiFunction<SSLEngine, List<String>, String>) + GET_HANDSHAKE_APPLICATION_PROTOCOL_SELECTOR.invoke(engine); + } catch (UnsupportedOperationException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } +} diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java b/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java index cd3fe15051d..8d2c4109df1 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java @@ -16,13 +16,18 @@ package io.netty.handler.ssl; import io.netty.buffer.ByteBufAllocator; +import io.netty.util.internal.PlatformDependent; + import javax.net.ssl.SSLEngine; /** * The {@link JdkApplicationProtocolNegotiator} to use if you need ALPN and are using {@link SslProvider#JDK}. */ public final class JdkAlpnApplicationProtocolNegotiator extends JdkBaseApplicationProtocolNegotiator { - private static final boolean AVAILABLE = Conscrypt.isAvailable() || JettyAlpnSslEngine.isAvailable(); + private static final boolean AVAILABLE = Conscrypt.isAvailable() || + jdkAlpnSupported() || + JettyAlpnSslEngine.isAvailable(); + private static final SslEngineWrapperFactory ALPN_WRAPPER = AVAILABLE ? new AlpnWrapper() : new FailureWrapper(); /** @@ -126,6 +131,9 @@ public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc, return isServer ? ConscryptAlpnSslEngine.newServerEngine(engine, alloc, applicationNegotiator) : ConscryptAlpnSslEngine.newClientEngine(engine, alloc, applicationNegotiator); } + if (jdkAlpnSupported()) { + return new Java9SslEngine(engine, applicationNegotiator, isServer); + } if (JettyAlpnSslEngine.isAvailable()) { return isServer ? JettyAlpnSslEngine.newServerEngine(engine, applicationNegotiator) : JettyAlpnSslEngine.newClientEngine(engine, applicationNegotiator); @@ -133,4 +141,8 @@ public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc, throw new RuntimeException("Unable to wrap SSLEngine of type " + engine.getClass().getName()); } } + + static boolean jdkAlpnSupported() { + return PlatformDependent.javaVersion() >= 9 && Java9SslUtils.supportsAlpn(); + } } diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java b/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java index fc326f6488a..8e20c9b1b1c 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkBaseApplicationProtocolNegotiator.java @@ -137,14 +137,14 @@ static class NoFailProtocolSelector implements ProtocolSelector { @Override public void unsupported() { - engineWrapper.getSession().setApplicationProtocol(null); + engineWrapper.setApplicationProtocol(null); } @Override public String select(List<String> protocols) throws Exception { for (String p : supportedProtocols) { if (protocols.contains(p)) { - engineWrapper.getSession().setApplicationProtocol(p); + engineWrapper.setApplicationProtocol(p); return p; } } @@ -152,7 +152,7 @@ public String select(List<String> protocols) throws Exception { } public String noSelectMatchFound() throws Exception { - engineWrapper.getSession().setApplicationProtocol(null); + engineWrapper.setApplicationProtocol(null); return null; } } @@ -179,13 +179,13 @@ private static class NoFailProtocolSelectionListener implements ProtocolSelectio @Override public void unsupported() { - engineWrapper.getSession().setApplicationProtocol(null); + engineWrapper.setApplicationProtocol(null); } @Override public void selected(String protocol) throws Exception { if (supportedProtocols.contains(protocol)) { - engineWrapper.getSession().setApplicationProtocol(protocol); + engineWrapper.setApplicationProtocol(protocol); } else { noSelectedMatchFound(protocol); } diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java index 680eea6195c..1cc3bdfa32a 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkSslEngine.java @@ -24,18 +24,26 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; -class JdkSslEngine extends SSLEngine { +class JdkSslEngine extends SSLEngine implements ApplicationProtocolAccessor { private final SSLEngine engine; - private final JdkSslSession session; + private volatile String applicationProtocol; JdkSslEngine(SSLEngine engine) { this.engine = engine; - session = new JdkSslSession(engine); } @Override - public JdkSslSession getSession() { - return session; + public String getApplicationProtocol() { + return applicationProtocol; + } + + void setApplicationProtocol(String applicationProtocol) { + this.applicationProtocol = applicationProtocol; + } + + @Override + public SSLSession getSession() { + return engine.getSession(); } public SSLEngine getWrappedEngine() { diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkSslSession.java b/handler/src/main/java/io/netty/handler/ssl/JdkSslSession.java deleted file mode 100644 index 183c2966327..00000000000 --- a/handler/src/main/java/io/netty/handler/ssl/JdkSslSession.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package io.netty.handler.ssl; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSessionContext; -import javax.security.cert.X509Certificate; -import java.security.Principal; -import java.security.cert.Certificate; - -final class JdkSslSession implements SSLSession, ApplicationProtocolAccessor { - private final SSLEngine engine; - private volatile String applicationProtocol; - - JdkSslSession(SSLEngine engine) { - this.engine = engine; - } - - private SSLSession unwrap() { - return engine.getSession(); - } - - @Override - public String getProtocol() { - return unwrap().getProtocol(); - } - - @Override - public String getApplicationProtocol() { - return applicationProtocol; - } - - void setApplicationProtocol(String applicationProtocol) { - this.applicationProtocol = applicationProtocol; - } - - @Override - public byte[] getId() { - return unwrap().getId(); - } - - @Override - public SSLSessionContext getSessionContext() { - return unwrap().getSessionContext(); - } - - @Override - public long getCreationTime() { - return unwrap().getCreationTime(); - } - - @Override - public long getLastAccessedTime() { - return unwrap().getLastAccessedTime(); - } - - @Override - public void invalidate() { - unwrap().invalidate(); - } - - @Override - public boolean isValid() { - return unwrap().isValid(); - } - - @Override - public void putValue(String s, Object o) { - unwrap().putValue(s, o); - } - - @Override - public Object getValue(String s) { - return unwrap().getValue(s); - } - - @Override - public void removeValue(String s) { - unwrap().removeValue(s); - } - - @Override - public String[] getValueNames() { - return unwrap().getValueNames(); - } - - @Override - public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { - return unwrap().getPeerCertificates(); - } - - @Override - public Certificate[] getLocalCertificates() { - return unwrap().getLocalCertificates(); - } - - @Override - public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { - return unwrap().getPeerCertificateChain(); - } - - @Override - public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { - return unwrap().getPeerPrincipal(); - } - - @Override - public Principal getLocalPrincipal() { - return unwrap().getLocalPrincipal(); - } - - @Override - public String getCipherSuite() { - return unwrap().getCipherSuite(); - } - - @Override - public String getPeerHost() { - return unwrap().getPeerHost(); - } - - @Override - public int getPeerPort() { - return unwrap().getPeerPort(); - } - - @Override - public int getPacketBufferSize() { - return unwrap().getPacketBufferSize(); - } - - @Override - public int getApplicationBufferSize() { - return unwrap().getApplicationBufferSize(); - } -} diff --git a/handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java index 624719a5be9..ce9f14a57e7 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/JettyAlpnSslEngine.java @@ -38,7 +38,6 @@ static boolean isAvailable() { } private static boolean initAvailable() { - // TODO: Add support for ALPN when using Java9 and still be able to configure it the Netty way. if (PlatformDependent.javaVersion() <= 8) { try { // Always use bootstrap class loader. diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java index 9878a87d43d..2670e53b23d 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java @@ -87,7 +87,7 @@ * the instance depends upon are released. Otherwise if any method of this class is called which uses the * the {@link ReferenceCountedOpenSslContext} JNI resources the JVM may crash. */ -public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted { +public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted, ApplicationProtocolAccessor { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountedOpenSslEngine.class); @@ -159,6 +159,7 @@ private enum HandshakeState { private boolean renegotiationPending; private boolean receivedShutdown; private volatile int destroyed; + private volatile String applicationProtocol; // Reference Counting private final ResourceLeakTracker<ReferenceCountedOpenSslEngine> leak; @@ -1827,7 +1828,12 @@ final boolean checkSniHostnameMatch(String hostname) { return Java8SslUtils.checkSniHostnameMatch(matchers, hostname); } - private final class OpenSslSession implements SSLSession, ApplicationProtocolAccessor { + @Override + public String getApplicationProtocol() { + return applicationProtocol; + } + + private final class OpenSslSession implements SSLSession { private final OpenSslSessionContext sessionContext; // These are guarded by synchronized(OpenSslEngine.this) as handshakeFinished() may be triggered by any @@ -1835,7 +1841,6 @@ private final class OpenSslSession implements SSLSession, ApplicationProtocolAcc private X509Certificate[] x509PeerCerts; private Certificate[] peerCerts; private String protocol; - private String applicationProtocol; private String cipher; private byte[] id; private long creationTime; @@ -2043,14 +2048,14 @@ private void selectApplicationProtocol() throws SSLException { case ALPN: applicationProtocol = SSL.getAlpnSelected(ssl); if (applicationProtocol != null) { - this.applicationProtocol = selectApplicationProtocol( + ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol( protocols, behavior, applicationProtocol); } break; case NPN: applicationProtocol = SSL.getNextProtoNegotiated(ssl); if (applicationProtocol != null) { - this.applicationProtocol = selectApplicationProtocol( + ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol( protocols, behavior, applicationProtocol); } break; @@ -2060,7 +2065,7 @@ private void selectApplicationProtocol() throws SSLException { applicationProtocol = SSL.getNextProtoNegotiated(ssl); } if (applicationProtocol != null) { - this.applicationProtocol = selectApplicationProtocol( + ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol( protocols, behavior, applicationProtocol); } break; @@ -2159,13 +2164,6 @@ public String getProtocol() { return protocol; } - @Override - public String getApplicationProtocol() { - synchronized (ReferenceCountedOpenSslEngine.this) { - return applicationProtocol; - } - } - @Override public String getPeerHost() { return ReferenceCountedOpenSslEngine.this.getPeerHost(); diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index b03417d15e3..3724b772719 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -573,12 +573,12 @@ public SSLEngine engine() { * @return the protocol name or {@code null} if application-level protocol has not been negotiated */ public String applicationProtocol() { - SSLSession sess = engine().getSession(); - if (!(sess instanceof ApplicationProtocolAccessor)) { + SSLEngine engine = engine(); + if (!(engine instanceof ApplicationProtocolAccessor)) { return null; } - return ((ApplicationProtocolAccessor) sess).getApplicationProtocol(); + return ((ApplicationProtocolAccessor) engine).getApplicationProtocol(); } /** diff --git a/pom.xml b/pom.xml index ba17e15111b..84c370792c5 100644 --- a/pom.xml +++ b/pom.xml @@ -710,6 +710,7 @@ <!-- JDK 8 --> <ignore>java.util.concurrent.atomic.LongAdder</ignore> + <ignore>java.util.function.BiFunction</ignore> <!-- Resolver --> <ignore>java.net.InetAddress</ignore>
diff --git a/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java b/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java index c1205130fc5..110871b3603 100644 --- a/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/JdkSslEngineTest.java @@ -25,6 +25,8 @@ import java.security.Provider; import java.util.ArrayList; import java.util.Collection; + +import io.netty.util.internal.PlatformDependent; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,7 +45,7 @@ @RunWith(Parameterized.class) public class JdkSslEngineTest extends SSLEngineTest { public enum ProviderType { - NPN_DEFAULT { + NPN_JETTY { @Override boolean isAvailable() { return JettyNpnSslEngine.isAvailable(); @@ -59,7 +61,7 @@ Provider provider() { return null; } }, - ALPN_DEFAULT { + ALPN_JETTY { @Override boolean isAvailable() { return JettyAlpnSslEngine.isAvailable(); @@ -76,6 +78,23 @@ Provider provider() { return null; } }, + ALPN_JAVA9 { + @Override + boolean isAvailable() { + return PlatformDependent.javaVersion() >= 9 && Java9SslUtils.supportsAlpn(); + } + + @Override + Protocol protocol() { + return Protocol.ALPN; + } + + @Override + Provider provider() { + // Use the default provider. + return null; + } + }, ALPN_CONSCRYPT { private Provider provider; @@ -178,7 +197,7 @@ public void testTlsExtensionNoCompatibleProtocolsNoHandshakeFailure() throws Exc public void testTlsExtensionNoCompatibleProtocolsClientHandshakeFailure() throws Exception { try { providerType.activate(this); - if (providerType == ProviderType.NPN_DEFAULT) { + if (providerType == ProviderType.NPN_JETTY) { ApplicationProtocolConfig clientApn = failingNegotiator(providerType.protocol(), PREFERRED_APPLICATION_LEVEL_PROTOCOL); ApplicationProtocolConfig serverApn = acceptingNegotiator(providerType.protocol(), @@ -249,7 +268,7 @@ public void testTlsExtensionNoCompatibleProtocolsServerHandshakeFailure() throws public void testAlpnCompatibleProtocolsDifferentClientOrder() throws Exception { try { providerType.activate(this); - if (providerType == ProviderType.NPN_DEFAULT) { + if (providerType == ProviderType.NPN_JETTY) { // This test only applies to ALPN. throw tlsExtensionNotFound(providerType.protocol()); } @@ -314,16 +333,14 @@ protected Provider serverSslContextProvider() { return provider; } - private ApplicationProtocolConfig failingNegotiator(Protocol protocol, - String... supportedProtocols) { + private static ApplicationProtocolConfig failingNegotiator(Protocol protocol, String... supportedProtocols) { return new ApplicationProtocolConfig(protocol, SelectorFailureBehavior.FATAL_ALERT, SelectedListenerFailureBehavior.FATAL_ALERT, supportedProtocols); } - private ApplicationProtocolConfig acceptingNegotiator(Protocol protocol, - String... supportedProtocols) { + private static ApplicationProtocolConfig acceptingNegotiator(Protocol protocol, String... supportedProtocols) { return new ApplicationProtocolConfig(protocol, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT,
train
train
"2017-08-24T07:40:47"
"2017-07-02T05:27:58Z"
rschmitt
val
netty/netty/7156_7157
netty/netty
netty/netty/7156
netty/netty/7157
[ "timestamp(timedelta=22.0, similarity=0.9158764485680886)" ]
d9d0e633dc69b9b93139d822eaa17b97ff3826ab
5a93ae4c2afedcb5aca9d172c17df485616f4498
[ "@axtavt please check https://github.com/netty/netty/pull/7157", "Fixed by https://github.com/netty/netty/pull/7157" ]
[]
"2017-08-28T09:00:28Z"
[ "defect" ]
DefaultSocks5CommandRequest incorrectly rejects SOCKS5 commands with dstPort=0
### Expected behavior According to [SOCKS 5 spec](https://www.ietf.org/rfc/rfc1928.txt), dstPort = 0 is a valid value in case of UDP ASSOCIATE command: > If the client is not in possesion of the information at the time of the UDP ASSOCIATE, the client MUST use a port number and address of all zeros. ### Actual behavior However, constructor of DefaultSocks5CommandRequest rejects this value as invalid: if (dstPort <= 0 || dstPort >= 65536) { throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 1~65535)"); } ### Netty version 4.1.15.Final
[ "codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java" ]
[ "codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java" ]
[ "codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java" ]
diff --git a/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java b/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java index d90150ebc24..ddd35fd6250 100755 --- a/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java +++ b/codec-socks/src/main/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequest.java @@ -59,8 +59,8 @@ public DefaultSocks5CommandRequest( } } - if (dstPort <= 0 || dstPort >= 65536) { - throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 1~65535)"); + if (dstPort < 0 || dstPort > 65535) { + throw new IllegalArgumentException("dstPort: " + dstPort + " (expected: 0~65535)"); } this.type = type;
diff --git a/codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java b/codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java index e4dc2dade7a..3b3b5db5281 100755 --- a/codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java +++ b/codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5CommandRequestTest.java @@ -76,7 +76,7 @@ public void testIDNNotExceeds255CharsLimit() { public void testValidPortRange() { try { new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, - "παράδειγμα.δοκιμήπαράδει", 0); + "παράδειγμα.δοκιμήπαράδει", -1); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } @@ -87,5 +87,10 @@ public void testValidPortRange() { } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } + + new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, + "παράδειγμα.δοκιμήπαράδει", 0); + new DefaultSocks5CommandRequest(Socks5CommandType.BIND, Socks5AddressType.DOMAIN, + "παράδειγμα.δοκιμήπαράδει", 65535); } }
train
train
"2017-08-28T20:21:57"
"2017-08-27T18:44:23Z"
axtavt
val
netty/netty/7083_7160
netty/netty
netty/netty/7083
netty/netty/7160
[ "timestamp(timedelta=11.0, similarity=0.8930761190728315)" ]
d9d0e633dc69b9b93139d822eaa17b97ff3826ab
4e9348da823491a9a8e299e8cf7d4ecad3cb6d28
[ "@amizurov maybe you want to submit a PR and just make it configurable via a constructor argument (and using the current behaviour by default) ?", "@normanmaurer Ok, with great pleasure.", "Fixed by https://github.com/netty/netty/pull/7160" ]
[ "For splitting with one-char String better use `String#split` instead of `Pattern`, [there is an optimization for this](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java#l2316).", "@fenik17 Thanks, I agree it is better approach for this case.", "nit: you can remove the final here.", "nit: remove the final to make it consistent", "call `channel.finish()` and validate the return value", "`getBytes(CharsetUtil.US_ASCII)`", "`getBytes(CharsetUtil.US_ASCII)`", "assert return value", "assert return value", "@After\r\n public void teardown() throws Exception {\r\n assertFalse(channel.finish());\r\n }", "ah sorry missed this 👍 ", "sorry for be a pita but just merge the two lines above^^", "sorry for be a pita but just merge the two lines above^^", "Did miss this before but just do:\r\n\r\n```java\r\nByteBuf invalidIncoming = Unpooled.copiedBuffer(StompTestConstants.FRAME_WITH_INVALID_HEADER, CharsetUtil.US_ASCII);\r\n```", "Did miss this before but just do:\r\n\r\n```java\r\nByteBuf invalidIncoming = Unpooled.copiedBuffer(StompTestConstants.FRAME_WITH_INVALID_HEADER, CharsetUtil.US_ASCII);\r\n```", "remove `EmbeddedChannel` here to ensure `channel.finish()` is called on the correct instance later on.", "can you move this to the other final fields and so group these together." ]
"2017-08-28T21:01:33Z"
[]
StompSubframeDecoder.redHeaders no any notification when parsed line that contains multiple colon
### Expected behavior By STOMP 1.2 specification - header name or value include any octet except CR or LF or ":". I understand that we can not just change the current behavior because of compatibility, but maybe we can add some kind of error notification ? ### Actual behavior We can built stomp frame that contain invalid header. And also when decoder parsed line it simply skips it without any notification error. ### Steps to reproduce Build DefaultStompFrame for any command with invalid header (time:2017-01-01T00:00:00) and then decoded message, header missing. ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.13 ### JVM version (e.g. `java -version`) 1.8.0_131 ### OS version (e.g. `uname -a`) ProductName: Mac OS X ProductVersion: 10.12.6
[ "codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java" ]
[ "codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java" ]
[ "codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeDecoderTest.java", "codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompTestConstants.java" ]
diff --git a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java index e25c15447ac..3ce55f21cbe 100644 --- a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java +++ b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeDecoder.java @@ -15,6 +15,9 @@ */ package io.netty.handler.codec.stomp; +import java.util.List; +import java.util.Locale; + import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; @@ -25,9 +28,6 @@ import io.netty.handler.codec.stomp.StompSubframeDecoder.State; import io.netty.util.internal.AppendableCharSequence; -import java.util.List; -import java.util.Locale; - import static io.netty.buffer.ByteBufUtil.indexOf; import static io.netty.buffer.ByteBufUtil.readBytes; @@ -71,6 +71,7 @@ enum State { private final int maxLineLength; private final int maxChunkSize; + private final boolean validateHeaders; private int alreadyReadChunkSize; private LastStompContentSubframe lastContent; private long contentLength = -1; @@ -79,7 +80,15 @@ public StompSubframeDecoder() { this(DEFAULT_MAX_LINE_LENGTH, DEFAULT_CHUNK_SIZE); } + public StompSubframeDecoder(boolean validateHeaders) { + this(DEFAULT_MAX_LINE_LENGTH, DEFAULT_CHUNK_SIZE, validateHeaders); + } + public StompSubframeDecoder(int maxLineLength, int maxChunkSize) { + this(maxLineLength, maxChunkSize, false); + } + + public StompSubframeDecoder(int maxLineLength, int maxChunkSize, boolean validateHeaders) { super(State.SKIP_CONTROL_CHARACTERS); if (maxLineLength <= 0) { throw new IllegalArgumentException( @@ -93,6 +102,7 @@ public StompSubframeDecoder(int maxLineLength, int maxChunkSize) { } this.maxChunkSize = maxChunkSize; this.maxLineLength = maxLineLength; + this.validateHeaders = validateHeaders; } @Override @@ -134,7 +144,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t if (toRead > maxChunkSize) { toRead = maxChunkSize; } - if (this.contentLength >= 0) { + if (contentLength >= 0) { int remainingLength = (int) (contentLength - alreadyReadChunkSize); if (toRead > remainingLength) { toRead = remainingLength; @@ -214,11 +224,14 @@ private State readHeaders(ByteBuf buffer, StompHeaders headers) { String[] split = line.split(":"); if (split.length == 2) { headers.add(split[0], split[1]); + } else if (validateHeaders) { + throw new IllegalArgumentException("a header value or name contains a prohibited character ':'" + + ", " + line); } } else { if (headers.contains(StompHeaders.CONTENT_LENGTH)) { - this.contentLength = getContentLength(headers, 0); - if (this.contentLength == 0) { + contentLength = getContentLength(headers, 0); + if (contentLength == 0) { return State.FINALIZE_FRAME_READ; } }
diff --git a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeDecoderTest.java b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeDecoderTest.java index 5b9b97e32c8..fe772126a55 100644 --- a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeDecoderTest.java +++ b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeDecoderTest.java @@ -18,12 +18,19 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; -import io.netty.util.CharsetUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.*; +import static io.netty.handler.codec.stomp.StompTestConstants.FRAME_WITH_INVALID_HEADER; +import static io.netty.util.CharsetUtil.US_ASCII; +import static io.netty.util.CharsetUtil.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; public class StompSubframeDecoderTest { @@ -69,7 +76,7 @@ public void testSingleFrameWithBodyAndContentLength() { StompContentSubframe content = channel.readInbound(); assertTrue(content instanceof LastStompContentSubframe); - String s = content.content().toString(CharsetUtil.UTF_8); + String s = content.content().toString(UTF_8); assertEquals("hello, queue a!!!", s); content.release(); @@ -88,7 +95,7 @@ public void testSingleFrameWithBodyWithoutContentLength() { StompContentSubframe content = channel.readInbound(); assertTrue(content instanceof LastStompContentSubframe); - String s = content.content().toString(CharsetUtil.UTF_8); + String s = content.content().toString(UTF_8); assertEquals("hello, queue a!", s); content.release(); @@ -108,22 +115,22 @@ public void testSingleFrameChunked() { assertEquals(StompCommand.SEND, frame.command()); StompContentSubframe content = channel.readInbound(); - String s = content.content().toString(CharsetUtil.UTF_8); + String s = content.content().toString(UTF_8); assertEquals("hello", s); content.release(); content = channel.readInbound(); - s = content.content().toString(CharsetUtil.UTF_8); + s = content.content().toString(UTF_8); assertEquals(", que", s); content.release(); content = channel.readInbound(); - s = content.content().toString(CharsetUtil.UTF_8); + s = content.content().toString(UTF_8); assertEquals("ue a!", s); content.release(); content = channel.readInbound(); - s = content.content().toString(CharsetUtil.UTF_8); + s = content.content().toString(UTF_8); assertEquals("!!", s); content.release(); @@ -155,4 +162,36 @@ public void testMultipleFramesDecoding() { assertNull(channel.readInbound()); } + + @Test + public void testValidateHeadersDecodingDisabled() { + ByteBuf invalidIncoming = Unpooled.copiedBuffer(FRAME_WITH_INVALID_HEADER.getBytes(US_ASCII)); + assertTrue(channel.writeInbound(invalidIncoming)); + + StompHeadersSubframe frame = channel.readInbound(); + assertNotNull(frame); + assertEquals(StompCommand.SEND, frame.command()); + assertTrue(frame.headers().contains("destination")); + assertTrue(frame.headers().contains("content-type")); + assertFalse(frame.headers().contains("current-time")); + + StompContentSubframe content = channel.readInbound(); + String s = content.content().toString(UTF_8); + assertEquals("some body", s); + content.release(); + } + + @Test + public void testValidateHeadersDecodingEnabled() { + channel = new EmbeddedChannel(new StompSubframeDecoder(true)); + + ByteBuf invalidIncoming = Unpooled.copiedBuffer(FRAME_WITH_INVALID_HEADER.getBytes(US_ASCII)); + assertTrue(channel.writeInbound(invalidIncoming)); + + StompHeadersSubframe frame = channel.readInbound(); + assertNotNull(frame); + assertTrue(frame.decoderResult().isFailure()); + assertEquals("a header value or name contains a prohibited character ':', current-time:2000-01-01T00:00:00", + frame.decoderResult().cause().getMessage()); + } } diff --git a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompTestConstants.java b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompTestConstants.java index 7d0de429122..0d89a5c3cc1 100644 --- a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompTestConstants.java +++ b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompTestConstants.java @@ -57,6 +57,12 @@ public final class StompTestConstants { '\n' + "body\0"; - private StompTestConstants() { } + public static final String FRAME_WITH_INVALID_HEADER = "SEND\n" + + "destination:/some-destination\n" + + "content-type:text/plain\n" + + "current-time:2000-01-01T00:00:00\n" + + '\n' + + "some body\0"; + private StompTestConstants() { } }
train
train
"2017-08-28T20:21:57"
"2017-08-10T15:21:17Z"
amizurov
val
netty/netty/7178_7180
netty/netty
netty/netty/7178
netty/netty/7180
[ "timestamp(timedelta=16.0, similarity=0.852711418881674)" ]
5c572f0f63da22392d477697c4c289072915d483
71a474a1082f43366416929c1df813d731eac441
[ "The stracktrace of the exception when running modified `Http2MultiplexCodecBuilderTest`.\r\n```\r\n15:49:13.120 [defaultEventLoop-1-1] WARN io.netty.channel.ChannelInitializer - Failed to initialize a channel. Closing: [id: 0x70bc891d, L:local:E:e07decb9 - R:local:io.netty.handler.codec.http2.http2multiplexcodecbuildertest](HTTP/2 - -1)\r\njava.lang.RuntimeException: should not be call for outbound stream\r\n\tat io.netty.handler.codec.http2.Http2MultiplexCodecBuilderTest$2.initChannel(Http2MultiplexCodecBuilderTest.java:89)\r\n\tat io.netty.channel.ChannelInitializer.initChannel(ChannelInitializer.java:113)\r\n\tat io.netty.channel.ChannelInitializer.handlerAdded(ChannelInitializer.java:105)\r\n\tat io.netty.channel.DefaultChannelPipeline.callHandlerAdded0(DefaultChannelPipeline.java:606)\r\n\tat io.netty.channel.DefaultChannelPipeline.access$15(DefaultChannelPipeline.java:604)\r\n\tat io.netty.channel.DefaultChannelPipeline$PendingHandlerAddedTask.execute(DefaultChannelPipeline.java:1412)\r\n\tat io.netty.channel.DefaultChannelPipeline.callHandlerAddedForAllHandlers(DefaultChannelPipeline.java:1131)\r\n\tat io.netty.channel.DefaultChannelPipeline.invokeHandlerAddedIfNeeded(DefaultChannelPipeline.java:656)\r\n\tat io.netty.channel.DefaultChannelPipeline$HeadContext.channelRegistered(DefaultChannelPipeline.java:1331)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRegistered(AbstractChannelHandlerContext.java:149)\r\n\tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRegistered(AbstractChannelHandlerContext.java:135)\r\n\tat io.netty.channel.DefaultChannelPipeline.fireChannelRegistered(DefaultChannelPipeline.java:829)\r\n\tat io.netty.handler.codec.http2.Http2MultiplexCodec$DefaultHttp2StreamChannel$Http2ChannelUnsafe.register(Http2MultiplexCodec.java:799)\r\n\tat io.netty.channel.SingleThreadEventLoop.register(SingleThreadEventLoop.java:80)\r\n\tat io.netty.channel.SingleThreadEventLoop.register(SingleThreadEventLoop.java:74)\r\n\tat io.netty.handler.codec.http2.Http2StreamChannelBootstrap.open0(Http2StreamChannelBootstrap.java:143)\r\n\tat io.netty.handler.codec.http2.Http2StreamChannelBootstrap$1.run(Http2StreamChannelBootstrap.java:124)\r\n\tat io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)\r\n\tat io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)\r\n\tat io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138)\r\n\tat java.lang.Thread.run(Thread.java:745)\r\n```\r\nSeems in `Http2MultiplexCodec.DefaultHttp2StreamChannel.Http2ChannelUnsafe.register`\r\n, we always add the `inboundStreamHandler` to the pipeline of the `Http2Stream`, no matter it is inbound or not.\r\n\r\nhttps://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java#L795\r\n\r\n@normanmaurer ", "Yep.. not sure if this is a bug or not tho as you will need to have an handler that handles inbound frames as well here. @ejona86 WDYT?", "Yeah we need this handler to handle the inbound streams. But for outboud streams, we will provide one by calling `Http2StreamChannelBootstrap.handler`. ", "I agree that outbound streams should have their channel initializer specified via `Http2StreamChannelBootstrap.handler()`. `Http2MultiplexCodecBuilder`'s handler is only for inbound streams.", "Got it... let me do a fix quickly \n\n> Am 05.09.2017 um 17:10 schrieb Eric Anderson <notifications@github.com>:\n> \n> I agree that outbound streams should have their channel initializer specified via Http2StreamChannelBootstrap.handler(). Http2MultiplexCodecBuilder's handler is only for inbound streams.\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Should be fixed by https://github.com/netty/netty/pull/7180 . Please check", "Fixed by https://github.com/netty/netty/pull/7180" ]
[]
"2017-09-05T17:37:26Z"
[ "defect" ]
The ChannelHandler which is used to construct Http2MultiplexCodecBuilder will also be added to out bound streams
### Expected behavior The `ChannelHandler` which is used to construct `Http2MultiplexCodecBuilder` should only be added to remotely-created streams. ### Actual behavior It is also added to out bound streams. ### Steps to reproduce Modify `Http2MultiplexCodecBuilderTest`, replace the code in `setUp` ``` Bootstrap cb = new Bootstrap() .channel(LocalChannel.class) .group(group) .handler(new Http2MultiplexCodecBuilder(false, new TestChannelInitializer()).build()); ``` to ``` Bootstrap cb = new Bootstrap() .channel(LocalChannel.class) .group(group) .handler(new Http2MultiplexCodecBuilder(false, new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { throw new RuntimeException("should not be call for outbound stream"); } }).build()); ``` Then `createOutboundStream` and `multipleOutboundStreams` will both fail. ### Minimal yet complete reproducer code (or URL to code) Just apply this patch https://github.com/Apache9/netty/commit/2dcbae3109bbab5699dbfd64176694c8d43f69ca ### Netty version 4.1.15.Final ### JVM version (e.g. `java -version`) java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) ### OS version (e.g. `uname -a`) Linux zhangduo-ubuntu 4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java index 7cb3ec0c70e..db513d3dae8 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java @@ -239,7 +239,7 @@ final void onHttp2StreamStateChanged(ChannelHandlerContext ctx, Http2FrameStream break; } // fall-trough - DefaultHttp2StreamChannel childChannel = new DefaultHttp2StreamChannel(stream); + DefaultHttp2StreamChannel childChannel = new DefaultHttp2StreamChannel(stream, false); ChannelFuture future = ctx.channel().eventLoop().register(childChannel); if (future.isDone()) { registerDone(future); @@ -266,7 +266,7 @@ final void onHttp2StreamWritabilityChanged(ChannelHandlerContext ctx, Http2Frame // TODO: This is most likely not the best way to expose this, need to think more about it. final Http2StreamChannel newOutboundStream() { - return new DefaultHttp2StreamChannel(newStream()); + return new DefaultHttp2StreamChannel(newStream(), true); } @Override @@ -403,6 +403,7 @@ private final class DefaultHttp2StreamChannel extends DefaultAttributeMap implem private final ChannelPipeline pipeline; private final Http2FrameStream stream; private final ChannelPromise closePromise; + private final boolean outbound; private volatile boolean registered; private volatile boolean writable; @@ -427,8 +428,9 @@ private final class DefaultHttp2StreamChannel extends DefaultAttributeMap implem // channelReadComplete(...) DefaultHttp2StreamChannel next; - DefaultHttp2StreamChannel(Http2FrameStream stream) { + DefaultHttp2StreamChannel(Http2FrameStream stream, boolean outbound) { this.stream = stream; + this.outbound = outbound; ((Http2MultiplexCodecStream) stream).channel = this; pipeline = new DefaultChannelPipeline(this) { @Override @@ -791,8 +793,10 @@ public void register(EventLoop eventLoop, ChannelPromise promise) { registered = true; - // Add the handler to the pipeline now that we are registered. - pipeline().addLast(inboundStreamHandler); + if (!outbound) { + // Add the handler to the pipeline now that we are registered. + pipeline().addLast(inboundStreamHandler); + } promise.setSuccess();
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java index 383d17104c9..f798b021f70 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java @@ -32,6 +32,7 @@ import io.netty.channel.local.LocalServerChannel; import org.junit.After; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -82,7 +83,12 @@ protected void initChannel(Channel ch) throws Exception { Bootstrap cb = new Bootstrap() .channel(LocalChannel.class) .group(group) - .handler(new Http2MultiplexCodecBuilder(false, new TestChannelInitializer()).build()); + .handler(new Http2MultiplexCodecBuilder(false, new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) throws Exception { + Assert.fail("Should not be called for outbound streams"); + } + }).build()); clientChannel = cb.connect(serverAddress).sync().channel(); assertTrue(serverChannelLatch.await(5, SECONDS)); }
train
train
"2017-09-04T20:20:04"
"2017-09-05T07:53:55Z"
Apache9
val
netty/netty/7082_7181
netty/netty
netty/netty/7082
netty/netty/7181
[ "timestamp(timedelta=33555.0, similarity=0.883115206972504)" ]
de9e666493469d40fa9107a78f9ae421a05f9cf4
bdc899fab4d0ae22db35cb4da6d5b86e06c95fd6
[ "This is \"fixed\" by https://github.com/netty/netty/pull/7181 ... To make it short no it makes no sense.", "Fixed by #7181 ", "@normanmaurer - Can you explain why the policy suggested here \"makes no sense\"? The policy implemented in #7181 seems incomplete and may incorrectly report writability in a few cases:\r\n- depending on initial settings for outbound streams (https://github.com/netty/netty/pull/7181#discussion_r139296524)\r\n- depending on connection window\r\n- depending on channel writability" ]
[ "false positive ?", "I'm not seeing a `setStreamAndProperty()` for client-created streams... Should it be part of `Http2FrameCodec.writeHeadersFrame()`?\r\n\r\nIf `s == null` then the stream must be client-side, since newStream() on server-side is initialized immediately. Since the headers frame/first frame issue is handled elsewhere, this probably should never be called with `s == null` (other than the issue that it looks like `s` is always null on client-side).", "s/evulate/evaluate/", "for client side its triggered by this code path:\r\n\r\nhttps://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java#L397\r\n\r\n", "fixed", "Oh, I see now. I don't feel bad missing that slight-of-hand. That does look like it will break when hitting MAX_CONCURRENT_STREAMS since StreamBufferingEncoder won't create the stream immediately.\r\n\r\nSo if `s == null` here, then things are weird/broken elsewhere, so it shouldn't really matter whether we consider it writable or not.", "This may not be correct in all cases. The peer can send a settings frame with initial_window_size of 0 which would mean new streams are not writable. A server/client may do this if they are being overwhelmed and/or was overly optimistic about how many resources it initially advertised ... not sure how common it is in practice.\r\n\r\nWe should consider checking the peer's initial window size if this is a locally created stream.", "can we rename `writabilityChanged` to `checkForWritabilityChange` (or something similar)? At this point we are not indicating there is a writability change ... we are just checking if there has been a change.", "I guess we currently don't have a test which closes a channel after it has written to fast, to much, or the peer stops reading? Seems like a potentially \"flaky\" check to have here ... if conditions/tests change ... can you add a comment?", "The writability needs to be true so the application provides the initial headers. After we have the headers the stream exists and this won't be used any more. So the application shouldn't end up writing any DATA.", "I think what @ejona86 said is correct and so it should be correct @Scottmitch ", "Ahh I see ... yes this makes sense. Although we don't make the same consideration for trailers. We don't really know when the trailers will be written so it is possible the user will write data until not writable and then want to write trailers but if they are using channel writability to conditionally write then they will have to wait. Writing trailers maybe less common, but it seems strange to exhibit different behavior in these scenarios. ", "This has nothing to do with HEADERS vs DATA and how they are impacted by HTTP/2 flow control. It has everything to do with \"the stream doesn't exist before the initial headers.\" So I don't really see the trailers as being weird at all. If client could send multiple headers (say, like server can with 1xx codes) then we'd still want this same logic.", "Yip understood this is to facilitate stream creation." ]
"2017-09-06T07:09:52Z"
[]
h2childchan: DefaultHttp2StreamChannel initial writability
Currently the initial writability of `DefaultHttp2StreamChannel` is false if we have not yet created the underlying `Http2Stream` object. Typically a channel is default writability is true, unless conditions otherwise prohibit this. In the case of `DefaultHttp2StreamChannel` we should investigate if the following policy makes sense: the default state is writable unless the connection window has collapsed, and we may also want to consider the parent channel's writability. https://github.com/netty/netty/pull/6896#discussion_r132339750
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java index b1bcdd213a0..a0685899632 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java @@ -582,6 +582,11 @@ void onHttp2FrameStreamException(ChannelHandlerContext ctx, Http2FrameStreamExce ctx.fireExceptionCaught(cause); } + final boolean isWritable(DefaultHttp2FrameStream stream) { + Http2Stream s = stream.stream; + return s != null && connection().remote().flowController().isWritable(s); + } + private final class Http2RemoteFlowControllerListener implements Http2RemoteFlowController.Listener { @Override public void writabilityChanged(Http2Stream stream) { @@ -601,7 +606,7 @@ public void writabilityChanged(Http2Stream stream) { static class DefaultHttp2FrameStream implements Http2FrameStream { private volatile int id = -1; - private volatile Http2Stream stream; + volatile Http2Stream stream; DefaultHttp2FrameStream setStreamAndProperty(PropertyKey streamKey, Http2Stream stream) { assert id == -1 || stream.id() == id; diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java index db513d3dae8..373bb9bd489 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java @@ -231,16 +231,17 @@ final void onHttp2Frame(ChannelHandlerContext ctx, Http2Frame frame) { @Override final void onHttp2StreamStateChanged(ChannelHandlerContext ctx, Http2FrameStream stream) { + Http2MultiplexCodecStream s = (Http2MultiplexCodecStream) stream; + switch (stream.state()) { case HALF_CLOSED_REMOTE: case OPEN: - if (((Http2MultiplexCodecStream) stream).channel != null) { + if (s.channel != null) { // ignore if child channel was already created. break; } // fall-trough - DefaultHttp2StreamChannel childChannel = new DefaultHttp2StreamChannel(stream, false); - ChannelFuture future = ctx.channel().eventLoop().register(childChannel); + ChannelFuture future = ctx.channel().eventLoop().register(new DefaultHttp2StreamChannel(s, false)); if (future.isDone()) { registerDone(future); } else { @@ -248,7 +249,7 @@ final void onHttp2StreamStateChanged(ChannelHandlerContext ctx, Http2FrameStream } break; case CLOSED: - DefaultHttp2StreamChannel channel = ((Http2MultiplexCodecStream) stream).channel; + DefaultHttp2StreamChannel channel = s.channel; if (channel != null) { channel.streamClosed(); } @@ -395,17 +396,25 @@ private enum ReadState { READ_PROCESSED_OK_TO_PROCESS_MORE } + private boolean initialWritability(DefaultHttp2FrameStream stream) { + // If the stream id is not valid yet we will just mark the channel as writable as we will be notified + // about non-writability state as soon as the first Http2HeaderFrame is written (if needed). + // This should be good enough and simplify things a lot. + return !isStreamIdValid(stream.id()) || isWritable(stream); + } + // TODO: Handle writability changes due writing from outside the eventloop. private final class DefaultHttp2StreamChannel extends DefaultAttributeMap implements Http2StreamChannel { private final Http2StreamChannelConfig config = new Http2StreamChannelConfig(this); private final Http2ChannelUnsafe unsafe = new Http2ChannelUnsafe(); private final ChannelId channelId; private final ChannelPipeline pipeline; - private final Http2FrameStream stream; + private final DefaultHttp2FrameStream stream; private final ChannelPromise closePromise; private final boolean outbound; private volatile boolean registered; + // We start with the writability of the channel when creating the StreamChannel. private volatile boolean writable; private boolean closePending; @@ -428,9 +437,10 @@ private final class DefaultHttp2StreamChannel extends DefaultAttributeMap implem // channelReadComplete(...) DefaultHttp2StreamChannel next; - DefaultHttp2StreamChannel(Http2FrameStream stream, boolean outbound) { + DefaultHttp2StreamChannel(DefaultHttp2FrameStream stream, boolean outbound) { this.stream = stream; this.outbound = outbound; + writable = initialWritability(stream); ((Http2MultiplexCodecStream) stream).channel = this; pipeline = new DefaultChannelPipeline(this) { @Override @@ -484,8 +494,7 @@ public boolean isActive() { @Override public boolean isWritable() { - // TODO: Should we also take the parent channel into account ? - return isStreamIdValid(stream.id()) && writable; + return writable; } @Override @@ -1011,6 +1020,9 @@ public void operationComplete(ChannelFuture future) throws Exception { private void firstWriteComplete(ChannelFuture future, ChannelPromise promise) { Throwable cause = future.cause(); if (cause == null) { + // As we just finished our first write which made the stream-id valid we need to re-evaluate + // the writability of the channel. + writabilityChanged(Http2MultiplexCodec.this.isWritable(stream)); promise.setSuccess(); } else { promise.setFailure(cause);
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java index f798b021f70..c394689fb6b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java @@ -24,6 +24,7 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoopGroup; @@ -74,7 +75,34 @@ public void setUp() throws InterruptedException { @Override protected void initChannel(Channel ch) throws Exception { serverConnectedChannel = ch; - ch.pipeline().addLast(new Http2MultiplexCodecBuilder(true, serverLastInboundHandler).build()); + ch.pipeline().addLast(new Http2MultiplexCodecBuilder(true, new ChannelInitializer<Channel>() { + + @Override + protected void initChannel(Channel ch) throws Exception { + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + private boolean writable; + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + writable |= ctx.channel().isWritable(); + super.channelActive(ctx); + } + + @Override + public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { + writable |= ctx.channel().isWritable(); + super.channelWritabilityChanged(ctx); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + assertTrue(writable); + super.channelInactive(ctx); + } + }); + ch.pipeline().addLast(serverLastInboundHandler); + } + }).build()); serverChannelLatch.countDown(); } }); @@ -120,7 +148,7 @@ private Http2StreamChannel newOutboundStream(ChannelHandler handler) { } @Test - public void multipleOutboundStreams() { + public void multipleOutboundStreams() throws Exception { Http2StreamChannel childChannel1 = newOutboundStream(new TestChannelInitializer()); assertTrue(childChannel1.isActive()); assertFalse(isStreamIdValid(childChannel1.stream().id())); @@ -148,10 +176,12 @@ public void multipleOutboundStreams() { childChannel1.close(); childChannel2.close(); + + serverLastInboundHandler.checkException(); } @Test - public void createOutboundStream() { + public void createOutboundStream() throws Exception { Channel childChannel = newOutboundStream(new TestChannelInitializer()); assertTrue(childChannel.isRegistered()); assertTrue(childChannel.isActive()); @@ -178,10 +208,13 @@ public void createOutboundStream() { Http2ResetFrame rstFrame = serverLastInboundHandler.blockingReadInbound(); assertNotNull(rstFrame); assertEquals(3, rstFrame.stream().id()); + + serverLastInboundHandler.checkException(); } @Sharable private static class SharableLastInboundHandler extends LastInboundHandler { + @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelActive(); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java index acf33ee0220..e9b477fdfb5 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java @@ -372,7 +372,7 @@ public void outboundFlowControlWritability() { Http2StreamChannel childChannel = newOutboundStream(); assertTrue(childChannel.isActive()); - assertFalse(childChannel.isWritable()); + assertTrue(childChannel.isWritable()); childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers())); parentChannel.flush();
train
train
"2017-09-08T10:38:16"
"2017-08-10T15:01:47Z"
Scottmitch
val
netty/netty/7199_7200
netty/netty
netty/netty/7199
netty/netty/7200
[ "timestamp(timedelta=16585.0, similarity=0.9814131261476915)" ]
de9e666493469d40fa9107a78f9ae421a05f9cf4
249aa1238d72474b77642d432b7fc20595265009
[ "I don't believe Google is using it. No concerns here.", "Sounds fine to me. Searching around it seems like there may be some small projects using it on the Raspberry Pi or to talk to a wireless modem. They probably wouldn't be served fine using RXTX directly (says the person who hasn't looked at RXTX at all).", "Fixed by https://github.com/netty/netty/pull/7200", "Hi,\r\n\r\nI'm part of the Apache PLC4X (incubating) (http://plc4x.apache.org) project and we're currently implementing more and more industrial protocols (mainly ip based, but not exclusively). The Modbus protocol is now the first protocol we are implementing where the TCP version is just another layer on top of the old serial protocol. My first idea was to simply use Netty RxTxChannel and now read that's deprecated. Which path should I follow in order to implement the serial version of the driver?\r\n\r\nChris ", "@chrisdutz I guess the answer would be to implement your own `Channel` or fork what we have and maintain it. We just have not the expertise and time to maintain it anymore." ]
[ "Compiler in IntelliJ IDEA still is not allow `@Deprecated` in package-info's:\r\n> Error:(23, 1) java: modifier deprecated not allowed here", "Fixed it... ff592c8d5c54d6a81b17050f980c5d57299a5148" ]
"2017-09-10T07:07:09Z"
[ "discussion" ]
Mark transport-rxtx as `@deprecated`
https://github.com/netty/netty/pull/7198 just reminded me that I wanted to bring up the topic of mark transport-rxtx as `@deprecated` for some time. This is mainly driven because I think there is really no-one that maintain this one and there is no easy way for us to even test it. I think we should better concentrate and spend our time on the "real" core transports that are part of netty. @Scottmitch @ejona86 @trustin @carl-mastrangelo WDYT ?
[ "transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java" ]
[ "transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java", "transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java" ]
[]
diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java index 0fbf37e5140..c5a15e36ff7 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/DefaultRxtxChannelConfig.java @@ -36,7 +36,10 @@ /** * Default configuration class for RXTX device connections. + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated final class DefaultRxtxChannelConfig extends DefaultChannelConfig implements RxtxChannelConfig { private volatile int baudrate = 115200; diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java index d5751ce3963..314af9b92b3 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannel.java @@ -36,7 +36,10 @@ /** * A channel to a serial device using the RXTX library. + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated public class RxtxChannel extends OioByteStreamChannel { private static final RxtxDeviceAddress LOCAL_ADDRESS = new RxtxDeviceAddress("localhost"); diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java index dcd2ce1628b..788f7ebf8e7 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelConfig.java @@ -49,7 +49,10 @@ * <td>{@link RxtxChannelOption#WAIT_TIME}</td><td>{@link #setWaitTimeMillis(int)}</td> * </tr> * </table> + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated public interface RxtxChannelConfig extends ChannelConfig { enum Stopbits { /** diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java index ee0be2736f3..22a737a86e7 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxChannelOption.java @@ -22,7 +22,10 @@ /** * Option for configuring a serial port connection + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated public final class RxtxChannelOption<T> extends ChannelOption<T> { public static final ChannelOption<Integer> BAUD_RATE = valueOf(RxtxChannelOption.class, "BAUD_RATE"); diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java index 806c2f17975..e03e18dc0de 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/RxtxDeviceAddress.java @@ -20,7 +20,10 @@ /** * A {@link SocketAddress} subclass to wrap the serial port address of a RXTX * device (e.g. COM1, /dev/ttyUSB0). + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated public class RxtxDeviceAddress extends SocketAddress { private static final long serialVersionUID = -2907820090993709523L; diff --git a/transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java b/transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java index 31a0e090bf2..04beb30d6af 100644 --- a/transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java +++ b/transport-rxtx/src/main/java/io/netty/channel/rxtx/package-info.java @@ -16,5 +16,8 @@ /** * A serial and parallel port communication transport based on <a href="http://rxtx.qbang.org/">RXTX</a>. + * + * @deprecated this transport will be removed in the next major version. */ +@Deprecated package io.netty.channel.rxtx;
null
train
train
"2017-09-08T10:38:16"
"2017-09-08T21:58:32Z"
normanmaurer
val
netty/netty/7214_7215
netty/netty
netty/netty/7214
netty/netty/7215
[ "timestamp(timedelta=273.0, similarity=0.8671342247371197)" ]
14189140a0e07ab1cac8b91b49a787143870890e
1aacc1fc2ddbcdc807a7416757fea870eb9d5069
[ "Fixed " ]
[ "so created is more correct then ok ?", "@normanmaurer \r\nhttps://tools.ietf.org/html/rfc7540#section-8.2.1, \r\nThe PUSH_PROMISE frame contains a header block that contains a complete set of request header fields that the server attributes to the request.\r\nIn fact, the first time I used OK as the Http response status, I changed the status to Created by referring to the test case (In the previous test case, we used 201 CREATED).", "Since it is not appropriate to define the response status on the rfc7540 spec, I think it is not important to be 200 or 201.", "According to the rfc7540 specification,\r\n\r\n> https://tools.ietf.org/html/rfc7540#section-8.2.1\r\n> Server push is semantically equivalent to a server responding to a\r\n> request; however, in this case, that request is also sent by the\r\n> server, as a PUSH_PROMISE frame.\r\n\r\n> https://tools.ietf.org/html/rfc7540#section-8.2.2\r\n> After sending the PUSH_PROMISE frame, the server can begin delivering\r\n> the pushed response as a response (Section 8.1.2.4) on a server-\r\n> initiated stream that uses the promised stream identifier.", "@normanmaurer The server sends the request headers in PUSH_PROMISE.\r\nHowever, if you specify the response status in \"onPushPromiseRead\" to prevent NPE, 200 seems to be better than 201.\r\nWDYT?\r\n" ]
"2017-09-15T08:51:09Z"
[ "defect" ]
NPE in InboundHttp2ToHttpAdapter When a HTTP/2 PUSH_PROMISE comes in
### Expected behavior No null pointer exceptions ### Actual behavior When a HTTP/2 PUSH_PROMISE comes in, we call **onPushPromiseRead** in InboundHttp2ToHttpAdapter. This makes us create a FullHttpMessage, which eventually calls "HttpConversionUtil.parseStatus", which occurs always NPE because status is null. io.netty.handler.codec.http2.Http2Exception: Unrecognized HTTP status code 'null' encountered in translation to HTTP/1.x at io.netty.handler.codec.http2.Http2Exception.connectionError(Http2Exception.java:99) at io.netty.handler.codec.http2.HttpConversionUtil.parseStatus(HttpConversionUtil.java:182) at io.netty.handler.codec.http2.HttpConversionUtil.toHttpResponse(HttpConversionUtil.java:204) at io.netty.handler.codec.http2.InboundHttp2ToHttpAdapter.newMessage(InboundHttp2ToHttpAdapter.java:157) at io.netty.handler.codec.http2.InboundHttp2ToHttpAdapter.processHeadersBegin(InboundHttp2ToHttpAdapter.java:190) at io.netty.handler.codec.http2.InboundHttp2ToHttpAdapter.onPushPromiseRead(InboundHttp2ToHttpAdapter.java:299) at io.netty.handler.codec.http2.Http2FrameListenerDecorator.onPushPromiseRead(Http2FrameListenerDecorator.java:85) at io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onPushPromiseRead(DefaultHttp2ConnectionDecoder.java:478) at io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onPushPromiseRead(Http2InboundFrameLogger.java:112) at io.netty.handler.codec.http2.DefaultHttp2FrameReader$3.processFragment(DefaultHttp2FrameReader.java:565) at io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPushPromiseFrame(DefaultHttp2FrameReader.java:573) at io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:266) at io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) at io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) at io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:116) at io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:353) at io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:413) at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1273) at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1084) at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.NullPointerException at io.netty.handler.codec.http.HttpResponseStatus.parseLine(HttpResponseStatus.java:458) at io.netty.handler.codec.http2.HttpConversionUtil.parseStatus(HttpConversionUtil.java:175) ... 41 more ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.15.Final ### JVM version (e.g. `java -version`) java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) ### OS version (e.g. `uname -a`) Linux UD-sunggonsong 4.4.0-93-generic #116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java index 0c8ba812c62..8ab511ea42e 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapter.java @@ -29,6 +29,7 @@ import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR; import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR; import static io.netty.handler.codec.http2.Http2Exception.connectionError; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.util.internal.ObjectUtil.checkNotNull; /** @@ -296,6 +297,14 @@ public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promi Http2Headers headers, int padding) throws Http2Exception { // A push promise should not be allowed to add headers to an existing stream Http2Stream promisedStream = connection.stream(promisedStreamId); + if (headers.status() == null) { + // A PUSH_PROMISE frame has no Http response status. + // https://tools.ietf.org/html/rfc7540#section-8.2.1 + // Server push is semantically equivalent to a server responding to a + // request; however, in this case, that request is also sent by the + // server, as a PUSH_PROMISE frame. + headers.status(OK.codeAsText()); + } FullHttpMessage msg = processHeadersBegin(ctx, promisedStream, headers, false, false, false); if (msg == null) { throw connectionError(PROTOCOL_ERROR, "Push Promise Frame received for pre-existing stream id %d",
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java index 33393afc0a3..07fa916cbc3 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java @@ -498,7 +498,12 @@ public void run() throws Http2Exception { assertEquals(request, capturedRequests.get(0)); final Http2Headers http2Headers = new DefaultHttp2Headers().status(new AsciiString("200")); - final Http2Headers http2Headers2 = new DefaultHttp2Headers().status(new AsciiString("201")) + // The PUSH_PROMISE frame includes a header block that contains a + // complete set of request header fields that the server attributes to + // the request. + // https://tools.ietf.org/html/rfc7540#section-8.2.1 + // Therefore, we should consider the case where there is no Http response status. + final Http2Headers http2Headers2 = new DefaultHttp2Headers() .scheme(new AsciiString("https")) .authority(new AsciiString("example.org")); runInChannel(serverConnectedChannel, new Http2Runnable() {
train
train
"2017-09-14T23:51:20"
"2017-09-15T08:28:07Z"
durigon
val
netty/netty/7222_7228
netty/netty
netty/netty/7222
netty/netty/7228
[ "timestamp(timedelta=13.0, similarity=0.9515025860879004)" ]
9d56439aa1c221d38ee3b526c63d268c2e6f16c7
7418ac1205be4205c7461b3ace0a6507d6d22ef4
[ "@vietj please check https://github.com/netty/netty/pull/7228", "Fixed by https://github.com/netty/netty/pull/7228", "awesome!" ]
[]
"2017-09-19T04:33:52Z"
[ "improvement" ]
NativeLibraryLoader should check the result of ClassLoader#getResource method
### Expected behavior `NativeLibraryLoader` uses `ClassLoader#getResource` method that can return nulls when the resource cannot be found. The returned `url` variable should be checked for nullity and fail in a more usable manner than a `NullPointerException` ### Actual behavior `NativeLibraryLoader` fails with a `NullPointerException` (wrapped in `UnsatisfiedLinkError`) which does not give much information about the real cause of the failure. ``` java.lang.UnsatisfiedLinkError: could not load a native library: netty_transport_native_kqueue at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:178) at io.netty.channel.kqueue.Native.loadNativeLibrary(Native.java:114) at io.netty.channel.kqueue.Native.<clinit>(Native.java:54) at io.netty.channel.kqueue.KQueue.<clinit>(KQueue.java:33) at io.vertx.core.spi.transport.KQeueTransport.isAvailable(KQeueTransport.java:39) at io.vertx.core.spi.transport.NioTransport.nativeTransport(NioTransport.java:47) at io.vertx.core.spi.Transport.<clinit>(Transport.java:34) at io.vertx.core.impl.VertxImpl.<init>(VertxImpl.java:153) at io.vertx.core.impl.VertxImpl.<init>(VertxImpl.java:143) at io.vertx.core.impl.VertxFactoryImpl.vertx(VertxFactoryImpl.java:42) at io.vertx.core.Vertx.vertx(Vertx.java:91) at io.vertx.test.core.VertxTestBase.setUp(VertxTestBase.java:69) at io.vertx.test.core.HttpTestBase.setUp(HttpTestBase.java:46) at io.vertx.test.core.AsyncTestBase.before(AsyncTestBase.java:76) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55) at org.junit.rules.RunRules.evaluate(RunRules.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367) at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161) at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121) Caused by: java.lang.NullPointerException at io.netty.util.internal.NativeLibraryLoader.load(NativeLibraryLoader.java:147) ``` ### Steps to reproduce Use the KQueue dependency without a classifier on OSX. ### Netty version 4.1.15.Final ### JVM version (e.g. `java -version`) java version "1.8.0_144" ### OS version (e.g. `uname -a`) Darwin julien 15.6.0 Darwin Kernel Version 15.6.0: Fri Feb 17 10:21:18 PST 2017; root:xnu-3248.60.11.4.1~1/RELEASE_X86_64 x86_64
[ "common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java" ]
[ "common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java" ]
[ "common/src/test/java/io/netty/util/internal/NativeLibraryLoaderTest.java" ]
diff --git a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java index dc3e359a78b..a1ea75fc2f1 100644 --- a/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java +++ b/common/src/main/java/io/netty/util/internal/NativeLibraryLoader.java @@ -21,6 +21,7 @@ import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -125,22 +126,28 @@ public static void load(String originalName, ClassLoader loader) { String libname = System.mapLibraryName(name); String path = NATIVE_RESOURCE_HOME + libname; - URL url = loader.getResource(path); - if (url == null && PlatformDependent.isOsx()) { - if (path.endsWith(".jnilib")) { - url = loader.getResource(NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib"); - } else { - url = loader.getResource(NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib"); - } - } - - int index = libname.lastIndexOf('.'); - String prefix = libname.substring(0, index); - String suffix = libname.substring(index, libname.length()); InputStream in = null; OutputStream out = null; File tmpFile = null; + URL url = loader.getResource(path); try { + if (url == null) { + if (PlatformDependent.isOsx()) { + String fileName = path.endsWith(".jnilib") ? NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib" : + NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib"; + url = loader.getResource(fileName); + if (url == null) { + throw new FileNotFoundException(fileName); + } + } else { + throw new FileNotFoundException(path); + } + } + + int index = libname.lastIndexOf('.'); + String prefix = libname.substring(0, index); + String suffix = libname.substring(index, libname.length()); + tmpFile = File.createTempFile(prefix, suffix, WORKDIR); in = url.openStream(); out = new FileOutputStream(tmpFile);
diff --git a/common/src/test/java/io/netty/util/internal/NativeLibraryLoaderTest.java b/common/src/test/java/io/netty/util/internal/NativeLibraryLoaderTest.java new file mode 100644 index 00000000000..151e3fc5bc6 --- /dev/null +++ b/common/src/test/java/io/netty/util/internal/NativeLibraryLoaderTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.util.internal; + +import org.junit.Test; + +import java.io.FileNotFoundException; +import java.util.UUID; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class NativeLibraryLoaderTest { + + @Test + public void testFileNotFound() { + try { + NativeLibraryLoader.load(UUID.randomUUID().toString(), NativeLibraryLoaderTest.class.getClassLoader()); + fail(); + } catch (UnsatisfiedLinkError error) { + assertTrue(error.getCause() instanceof FileNotFoundException); + } + } +}
test
train
"2017-09-19T06:42:46"
"2017-09-18T08:42:42Z"
vietj
val
netty/netty/7253_7261
netty/netty
netty/netty/7253
netty/netty/7261
[ "timestamp(timedelta=152.0, similarity=0.8985595275090416)" ]
47f016bf564e9b86571fcb04d42f3ae327d0f58d
c0467df838349d5f3db4c1d3b66987ea950959e0
[ "@normanmaurer This looks related to https://github.com/netty/netty/commit/ecd6e5ce6d82756475e88ae69d2bfef1082edb68#diff-9cc075ed08ebc635ad5afcdb82bd449b I think we just need to add the `Content-Length` header for all cases, including when consumers use `preflightResponseHeader()` too.", "Pull request for the fix, including unit tests: https://github.com/netty/netty/pull/7261", "Fixed by https://github.com/netty/netty/pull/7261" ]
[ "`HttpHeaderValues.ZERO`", "`HtpHeaderValues.ZERO`", "No problem, I changed that in commit 9c5c89c55. I squashed commits too so there is a single commit message and reverting is easy. If I shouldn't do that let me know." ]
"2017-09-28T14:57:04Z"
[ "defect" ]
CorsHandler not responding with Content-Length
### Expected behavior * `CorsHandler` responds with `Content-Length: 0` when origin is allowed * `CorsHandler` responds with `Content-Length: 0` when origin is not allowed ### Actual behavior * `CorsHandler` responds with `Content-Length: 0` when origin is allowed * `CorsHandler` does not respond with a `Content-Length` header when origin is not allowed ### Steps to reproduce * Run an `NioEventGroupLoop` with a `CorsHandler` in the pipeline. (see code) * Make a request from an allowed origin, notice `Content-Length: 0` in the response. This is expected. (see code) * Make a request from an origin that is not allowed, notice no `Content-Length` header in the response. This is unexpected. (see code) ### Minimal yet complete reproducer code (or URL to code) Server side: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.cors.CorsConfigBuilder; import io.netty.handler.codec.http.cors.CorsHandler; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * Runs netty with a CORS handler on 8080 */ public class NettyCorsBugApp { private static final int PORT = 8080; private static final String ALLOWED_ORIGIN = "http://example.com"; public static void main(String[] args) throws Exception { EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(eventLoopGroup) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(1024 * 1024)); // 1MB pipeline.addLast(new CorsHandler( CorsConfigBuilder.forOrigin(ALLOWED_ORIGIN) .allowedRequestMethods(HttpMethod.POST) .build()) ); } }) .channel(NioServerSocketChannel.class); Channel channel = bootstrap.bind(PORT).sync().channel(); channel.closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } } ``` Client side from an allowed origin. Notice how curl exits. ``` $ curl -sv -X OPTIONS -H 'Origin: http://example.com' -H 'Access-Control-Request-Method: POST' http://localhost:8080 * Rebuilt URL to: http://localhost:8080/ * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > OPTIONS / HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.54.0 > Accept: */* > Origin: http://example.com > Access-Control-Request-Method: POST > < HTTP/1.1 200 OK < access-control-allow-origin: http://example.com < vary: origin < access-control-allow-methods: POST < access-control-allow-headers: < access-control-max-age: 0 < date: "Tue, 26 Sep 2017 20:03:53 GMT" < content-length: 0 < * Connection #0 to host localhost left intact ``` Client side from an origin that is not allowed. Notice how curl does not exit. ``` $ curl -sv -X OPTIONS -H 'Origin: http://invalid.com' -H 'Access-Control-Request-Method: POST' http://localhost:8080 * Rebuilt URL to: http://localhost:8080/ * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > OPTIONS / HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.54.0 > Accept: */* > Origin: http://invalid.com > Access-Control-Request-Method: POST > < HTTP/1.1 200 OK * no chunk, no close, no size. Assume close to signal end < ``` ### Netty version Tested `4.1.6-Final` and `4.1.16.Final`, same behavior. ### JVM version (e.g. `java -version`) ``` java version "1.8.0_131" Java(TM) SE Runtime Environment (build 1.8.0_131-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode) ``` ### OS version (e.g. `uname -a`) ``` Darwin WF14616 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64 ```
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java index 63bffe15f00..f4b5552b724 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java @@ -22,6 +22,7 @@ import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; @@ -81,6 +82,9 @@ private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest setMaxAge(response); setPreflightHeaders(response); } + if (!response.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) { + response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); + } release(request); respond(ctx, request, response); } @@ -205,8 +209,10 @@ public void write(final ChannelHandlerContext ctx, final Object msg, final Chann } private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) { + HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), FORBIDDEN); + response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO); release(request); - respond(ctx, request, new DefaultFullHttpResponse(request.protocolVersion(), FORBIDDEN)); + respond(ctx, request, response); } private static void respond(
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java index e3d67b6bf5a..f3fe97efd01 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java @@ -161,6 +161,7 @@ public void preflightRequestWithCustomHeader() { final HttpResponse response = preflightRequest(config, "http://localhost:8888", "content-type, xheader1"); assertThat(response.headers().get(of("CustomHeader")), equalTo("somevalue")); assertThat(response.headers().get(VARY), equalTo(ORIGIN.toString())); + assertThat(response.headers().get(CONTENT_LENGTH), is("0")); } @Test @@ -276,6 +277,7 @@ public void simpleRequestShortCircuit() { final CorsConfig config = forOrigin("http://localhost:8080").shortCircuit().build(); final HttpResponse response = simpleRequest(config, "http://localhost:7777"); assertThat(response.status(), is(FORBIDDEN)); + assertThat(response.headers().get(CONTENT_LENGTH), is("0")); } @Test
train
train
"2017-09-27T13:25:16"
"2017-09-27T15:22:44Z"
matthewbelisle-wf
val
netty/netty/7230_7277
netty/netty
netty/netty/7230
netty/netty/7277
[ "timestamp(timedelta=29.0, similarity=0.8598549436188782)" ]
5eca326c3568566f334b31b18f7866af19a989c8
3cf2b478c715fffb746de6ff756cf4bbe09fac63
[ "@BillyYccc please check https://github.com/netty/netty/pull/7277", "Fixed" ]
[ "![CRITICAL](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-critical.png) Remove this use of \"Thread.sleep()\". [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://garage.netty.io/sonarqube/coding_rules#rule_key=squid%3AS2925)\n", "This is needed...", "Swapping from `isDone()` to `await(10, MILLISECONDS)` is probably better.", "@ejona86 actually this will not work as then we will try to call await() on the EventLoop thread which will then throw an exception. " ]
"2017-10-05T08:24:18Z"
[ "defect" ]
Method setHandshakeTimeout of SslHandler does not work in server side
### Expected behavior I want to enable `setHandshakeTimeout()` in server side. I call the method setHandshakeTimeout() like this `sslHandler.setHandshakeTimeout(1,TimeUnit.MILLISECONDS);` The value of HandshakeTimeout is set to a very small value so that the client and server can not complete the handshake since the handshake is timeout. ### Actual behavior But it can not work when I use this in server.The connection can still be established between server and client. However when I do the same in client, the SSL connection can not be established , this is what I expect to see. ### Steps to reproduce 1. call the `sslHandler.setHandshakeTimeoutMillis(1);` or `sslHandler.setHandshakeTimeout(1,TimeUnit.MILLISECONDS);` in server 2. do connect and SSL connection can be successfully established 3. do 1 and 2 again in client side, and SSL connection can not be established ### Minimal yet complete reproducer code (or URL to code) You may use [SecureChat](http://netty.io/4.1/xref/io/netty/example/securechat/package-summary.html) example or any other SSL example to reproduce ### Netty version 4.1.15.Final ### JVM version (e.g. `java -version`) java version "1.8.0_131" Java(TM) SE Runtime Environment (build 1.8.0_131-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index ac32c9c76f0..f72cf874623 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -1536,11 +1536,15 @@ private void flush(ChannelHandlerContext ctx, ChannelPromise promise) throws Exc public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; - if (ctx.channel().isActive() && engine.getUseClientMode()) { - // Begin the initial handshake. - // channelActive() event has been fired already, which means this.channelActive() will - // not be invoked. We have to initialize here instead. - handshake(null); + if (ctx.channel().isActive()) { + if (engine.getUseClientMode()) { + // Begin the initial handshake. + // channelActive() event has been fired already, which means this.channelActive() will + // not be invoked. We have to initialize here instead. + handshake(null); + } else { + applyHandshakeTimeout(null); + } } else { // channelActive() event has not been fired yet. this.channelOpen() will be invoked // and initialization will occur there. @@ -1635,17 +1639,21 @@ public void operationComplete(Future<Channel> future) throws Exception { } finally { forceFlush(ctx); } + applyHandshakeTimeout(p); + } + private void applyHandshakeTimeout(Promise<Channel> p) { + final Promise<Channel> promise = p == null ? handshakePromise : p; // Set timeout if necessary. final long handshakeTimeoutMillis = this.handshakeTimeoutMillis; - if (handshakeTimeoutMillis <= 0 || p.isDone()) { + if (handshakeTimeoutMillis <= 0 || promise.isDone()) { return; } final ScheduledFuture<?> timeoutFuture = ctx.executor().schedule(new Runnable() { @Override public void run() { - if (p.isDone()) { + if (promise.isDone()) { return; } notifyHandshakeFailure(HANDSHAKE_TIMED_OUT); @@ -1653,7 +1661,7 @@ public void run() { }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); // Cancel the handshake timeout when handshake is finished. - p.addListener(new FutureListener<Channel>() { + promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(Future<Channel> f) throws Exception { timeoutFuture.cancel(false); @@ -1671,9 +1679,13 @@ private void forceFlush(ChannelHandlerContext ctx) { */ @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { - if (!startTls && engine.getUseClientMode()) { - // Begin the initial handshake - handshake(null); + if (!startTls) { + if (engine.getUseClientMode()) { + // Begin the initial handshake. + handshake(null); + } else { + applyHandshakeTimeout(null); + } } ctx.fireChannelActive(); }
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java index 5e10a6d569b..478c77400f0 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -85,6 +85,36 @@ public class SslHandlerTest { + @Test(expected = SSLException.class, timeout = 3000) + public void testClientHandshakeTimeout() throws Exception { + testHandshakeTimeout(true); + } + + @Test(expected = SSLException.class, timeout = 3000) + public void testServerHandshakeTimeout() throws Exception { + testHandshakeTimeout(false); + } + + private static void testHandshakeTimeout(boolean client) throws Exception { + SSLEngine engine = SSLContext.getDefault().createSSLEngine(); + engine.setUseClientMode(client); + SslHandler handler = new SslHandler(engine); + handler.setHandshakeTimeoutMillis(1); + + EmbeddedChannel ch = new EmbeddedChannel(handler); + try { + while (!handler.handshakeFuture().isDone()) { + Thread.sleep(10); + // We need to run all pending tasks as the handshake timeout is scheduled on the EventLoop. + ch.runPendingTasks(); + } + + handler.handshakeFuture().syncUninterruptibly(); + } finally { + ch.finishAndReleaseAll(); + } + } + @Test public void testTruncatedPacket() throws Exception { SSLEngine engine = SSLContext.getDefault().createSSLEngine();
train
train
"2017-10-05T08:26:42"
"2017-09-19T06:27:11Z"
BillyYccc
val
netty/netty/6100_7283
netty/netty
netty/netty/6100
netty/netty/7283
[ "timestamp(timedelta=1556.0, similarity=0.9223981932983233)" ]
5eca326c3568566f334b31b18f7866af19a989c8
f85039695d37aab08d41adf2319f2e066e039d1b
[]
[ "After updating animal-sniffer-maven-plugin.. should be fine as NioDatagramChannel only supports >= java17\r\n\r\n```text\r\n[INFO] --- animal-sniffer-maven-plugin:1.16:check (default) @ netty-transport ---\r\n[INFO] Checking unresolved references to org.codehaus.mojo.signature:java16:1.1\r\n[ERROR] /home/johno/Workspaces/netty/transport/src/main/java/io/netty/channel/socket/nio/NioDatagramChannel.java:104: Undefined reference: java.net.ProtocolFamily\r\n```" ]
"2017-10-07T08:34:43Z"
[]
Upgrade ASM dependency to 6.0.0 final once released
We need to upgrade our ASM dependency to 6.0.0 final once its released to also support compiling on java9. See https://issues.apache.org/jira/browse/MSHADE-242
[ "common/pom.xml", "pom.xml" ]
[ "common/pom.xml", "pom.xml" ]
[]
diff --git a/common/pom.xml b/common/pom.xml index 66efb88a2df..e8c7bf372f8 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -102,30 +102,6 @@ </configuration> </execution> </executions> - <!-- Needed to support JDK9 --> - <!-- See https://github.com/netty/netty/issues/6100 --> - <dependencies> - <dependency> - <groupId>org.ow2.asm</groupId> - <artifactId>asm</artifactId> - <version>${asm.version}</version> - </dependency> - <dependency> - <groupId>org.ow2.asm</groupId> - <artifactId>asm-commons</artifactId> - <version>${asm.version}</version> - </dependency> - <dependency> - <groupId>org.ow2.asm</groupId> - <artifactId>asm-analysis</artifactId> - <version>${asm.version}</version> - </dependency> - <dependency> - <groupId>org.ow2.asm</groupId> - <artifactId>asm-util</artifactId> - <version>${asm.version}</version> - </dependency> - </dependencies> </plugin> <!-- Add generated collection sources. --> <plugin> diff --git a/pom.xml b/pom.xml index 8c991db2857..bdc42a9dad3 100644 --- a/pom.xml +++ b/pom.xml @@ -77,10 +77,6 @@ <argLine.java9>--add-modules java.xml.bind ${argLine.java9.extras}</argLine.java9> <!-- Not use alpn agent as Java9 supports alpn out of the box --> <argLine.alpnAgent /> - <!-- This is needed as earlier ASM versions not support java9 --> - <!-- https://issues.apache.org/jira/browse/MSHADE-242 --> - <!-- https://github.com/netty/netty/issues/6100 --> - <asm.version>6.0_BETA</asm.version> <!-- Skip as maven plugin not works with Java9 yet --> <skipOsgiTestsuite>true</skipOsgiTestsuite> <forbiddenapis.skip>true</forbiddenapis.skip> @@ -200,7 +196,6 @@ <logging.config>${project.basedir}/../common/src/test/resources/logback-test.xml</logging.config> <logging.logLevel>debug</logging.logLevel> <log4j2.version>2.6.2</log4j2.version> - <asm.version>5.1</asm.version> <enforcer.plugin.version>1.4.1</enforcer.plugin.version> <testJavaHome>${env.JAVA_HOME}</testJavaHome> <skipOsgiTestsuite>false</skipOsgiTestsuite> @@ -641,15 +636,7 @@ be used even when compiling with java 1.7+ --> <groupId>org.codehaus.mojo</groupId> <artifactId>animal-sniffer-maven-plugin</artifactId> - <version>1.11</version> - <dependencies> - <!-- Upgrade ASM and support Java 8 bytecode --> - <dependency> - <groupId>org.ow2.asm</groupId> - <artifactId>asm-all</artifactId> - <version>${asm.version}</version> - </dependency> - </dependencies> + <version>1.16</version> <configuration> <signature> <groupId>org.codehaus.mojo.signature</groupId> @@ -704,6 +691,9 @@ <ignore>java.util.zip.CRC32</ignore> <ignore>java.util.zip.Adler32</ignore> + <!-- NioDatagramChannel implementation --> + <ignore>java.net.ProtocolFamily</ignore> + <!-- JDK 9 --> <ignore>java.nio.ByteBuffer</ignore> <ignore>java.nio.CharBuffer</ignore> @@ -1160,7 +1150,7 @@ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> - <version>2.4.3</version> + <version>3.1.0</version> </plugin> <!-- Workaround for the 'M2E plugin execution not covered' problem.
null
train
train
"2017-10-05T08:26:42"
"2016-12-03T08:08:47Z"
normanmaurer
val
netty/netty/7337_7338
netty/netty
netty/netty/7337
netty/netty/7338
[ "timestamp(timedelta=13352.0, similarity=0.8889366655100914)" ]
dcbbae7f9006f5b995d055702dd1c9f55f0e0c9d
addf44225db03b73b48e32f11106d00f40da13ad
[ "You are correct... let me fix it.", "Cool, thanks", "@Anon43590 please check https://github.com/netty/netty/pull/7338", "@normanmaurer looks correct to me, thanks" ]
[ "`transfered ` -> `transferred`" ]
"2017-10-24T12:21:25Z"
[ "defect" ]
Possible buffer leak in SslHandler?
Excuse me if I'm missing something obvious, but it seems to me that in SslHandler.java, "buf" removed from "pendingUnencryptedWrites" on line 751 may leak if "wrap(alloc, engine, buf, out)" called on line 762 throws. The wrap function on line 912 is marked as "throws SSLException", which I assume is something that could possibly happen and not be a fatal error for the entire server. So it seems like the aforementioned buffer had ought to be released if such an exception occurs, perhaps in the finally block on line 803. I only noticed this randomly while helping a coworker to track down an unrelated issue, so it's not like I've actually seen this leak happen.
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index c3920e68c4d..444ba2f4b4e 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -742,13 +742,14 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti ChannelPromise promise = null; ByteBufAllocator alloc = ctx.alloc(); boolean needUnwrap = false; + ByteBuf buf = null; try { final int wrapDataSize = this.wrapDataSize; // Only continue to loop if the handler was not removed in the meantime. // See https://github.com/netty/netty/issues/5860 while (!ctx.isRemoved()) { promise = ctx.newPromise(); - ByteBuf buf = wrapDataSize > 0 ? + buf = wrapDataSize > 0 ? pendingUnencryptedWrites.remove(alloc, wrapDataSize, promise) : pendingUnencryptedWrites.removeFirst(promise); if (buf == null) { @@ -763,6 +764,7 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti if (result.getStatus() == Status.CLOSED) { buf.release(); + buf = null; promise.tryFailure(SSLENGINE_CLOSED); promise = null; // SSLEngine has been closed already. @@ -775,6 +777,7 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti } else { buf.release(); } + buf = null; switch (result.getHandshakeStatus()) { case NEED_TASK: @@ -801,6 +804,10 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti } } } finally { + // Ownership of buffer was not transferred, release it. + if (buf != null) { + buf.release(); + } finishWrap(ctx, out, promise, inUnwrap, needUnwrap); } }
null
train
train
"2017-10-24T09:32:06"
"2017-10-24T12:04:30Z"
Anon43590
val
netty/netty/7353_7357
netty/netty
netty/netty/7353
netty/netty/7357
[ "timestamp(timedelta=23.0, similarity=0.8823948021739179)" ]
cdb2a27857e2dc0bc12ac97eaf2edd23a6467568
a03b3fc5d260e159875afcc5cb31ef41b1e6d650
[ "Will have a look tomorrow\n\n> Am 31.10.2017 um 17:07 schrieb Search Guard <notifications@github.com>:\n> \n> Expected behavior\n> \n> No NPE\n> \n> Actual behavior\n> \n> java.lang.NullPointerException: ssl (see stracktrace below) at ReferenceCountedOpenSslEngine.rejectRemoteInitiatedRenegotiation\n> \n> Steps to reproduce\n> \n> Happens randomly\n> \n> Minimal yet complete reproducer code (or URL to code)\n> \n> Netty version\n> \n> 4.1.13.Final with tcnative 2.0.5.Final and OpenSSL 1.0.2l 25 May 2017\n> \n> JVM version (e.g. java -version)\n> \n> java version \"1.8.0_121\"\n> Java(TM) SE Runtime Environment (build 1.8.0_121-b13)\n> Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)\n> \n> OS version (e.g. uname -a)\n> \n> Darwin MacBook-Pro.local 14.5.0 Darwin Kernel Version 14.5.0: Sun Jun 4 21:40:08 PDT 2017; root:xnu-2782.70.3~1/RELEASE_X86_64 x86_64\n> \n> io.netty.handler.codec.DecoderException: java.lang.NullPointerException: ssl\n> \tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459) ~[netty-codec-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) ~[netty-codec-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.nio.NioEventLoop.processSelectedKeysPlain(NioEventLoop.java:544) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:498) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) [netty-transport-4.1.13.Final.jar:4.1.13.Final]\n> \tat io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.13.Final.jar:4.1.13.Final]\n> \tat java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]\n> Caused by: java.lang.NullPointerException: ssl\n> \tat io.netty.internal.tcnative.SSL.getHandshakeCount(Native Method) ~[?:?]\n> \tat io.netty.handler.ssl.ReferenceCountedOpenSslEngine.rejectRemoteInitiatedRenegotiation(ReferenceCountedOpenSslEngine.java:985) ~[?:?]\n> \tat io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:948) ~[?:?]\n> \tat io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:994) ~[?:?]\n> \tat io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1037) ~[?:?]\n> \tat io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:206) ~[?:?]\n> \tat io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1162) ~[?:?]\n> \tat io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1084) ~[?:?]\n> \tat io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) ~[?:?]\n> \tat io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) ~[?:?]\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "@floragunncom thanks for reporting. Fixed in https://github.com/netty/netty/pull/7357", "Fixed by https://github.com/netty/netty/pull/7357", "@normanmaurer must be close to release day? 😎 ", "Yes\n\n> Am 03.11.2017 um 07:57 schrieb Johno Crawford <notifications@github.com>:\n> \n> @normanmaurer must be close to release day? 😎\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n" ]
[]
"2017-11-01T07:12:15Z"
[ "defect" ]
java.lang.NullPointerException: ssl at ReferenceCountedOpenSslEngine.rejectRemoteInitiatedRenegotiation
### Expected behavior No NPE ### Actual behavior java.lang.NullPointerException: ssl (see stracktrace below) at ReferenceCountedOpenSslEngine.rejectRemoteInitiatedRenegotiation ### Steps to reproduce Happens randomly ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.13.Final with tcnative 2.0.5.Final and OpenSSL 1.0.2l 25 May 2017 ### JVM version (e.g. `java -version`) java version "1.8.0_121" Java(TM) SE Runtime Environment (build 1.8.0_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode) ### OS version (e.g. `uname -a`) Darwin MacBook-Pro.local 14.5.0 Darwin Kernel Version 14.5.0: Sun Jun 4 21:40:08 PDT 2017; root:xnu-2782.70.3~1/RELEASE_X86_64 x86_64 <pre> io.netty.handler.codec.DecoderException: java.lang.NullPointerException: ssl at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459) ~[netty-codec-4.1.13.Final.jar:4.1.13.Final] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) ~[netty-codec-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeysPlain(NioEventLoop.java:544) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:498) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458) [netty-transport-4.1.13.Final.jar:4.1.13.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.13.Final.jar:4.1.13.Final] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121] Caused by: java.lang.NullPointerException: ssl at io.netty.internal.tcnative.SSL.getHandshakeCount(Native Method) ~[?:?] at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.rejectRemoteInitiatedRenegotiation(ReferenceCountedOpenSslEngine.java:985) ~[?:?] at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:948) ~[?:?] at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:994) ~[?:?] at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1037) ~[?:?] at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:206) ~[?:?] at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1162) ~[?:?] at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1084) ~[?:?] at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) ~[?:?] at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) ~[?:?] </pre>
[ "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java index 0c4bf5c2d47..5b2848e2373 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java @@ -1115,7 +1115,10 @@ private void closeAll() throws SSLException { } private void rejectRemoteInitiatedRenegotiation() throws SSLHandshakeException { - if (rejectRemoteInitiatedRenegotiation && SSL.getHandshakeCount(ssl) > 1) { + // As rejectRemoteInitiatedRenegotiation() is called in a finally block we also need to check if we shutdown + // the engine before as otherwise SSL.getHandshakeCount(ssl) will throw an NPE if the passed in ssl is 0. + // See https://github.com/netty/netty/issues/7353 + if (rejectRemoteInitiatedRenegotiation && !isDestroyed() && SSL.getHandshakeCount(ssl) > 1) { // TODO: In future versions me may also want to send a fatal_alert to the client and so notify it // that the renegotiation failed. shutdown();
null
val
train
"2017-10-29T13:42:15"
"2017-10-31T16:07:12Z"
floragunn
val
netty/netty/7378_7380
netty/netty
netty/netty/7378
netty/netty/7380
[ "timestamp(timedelta=6.0, similarity=0.8634903348220907)" ]
8618a3351cbecc68562c06c409538b182077f8d9
6b5e8d82e05a7732dc239a38429736ad016db6f9
[ "See https://github.com/netty/netty/pull/7380" ]
[]
"2017-11-07T16:45:36Z"
[ "defect" ]
Channel promise of a write is successful, although SSL handshake fails.
### Expected behavior When a SSL handshake fails, a channel promise of a write operation should fail aswell. ### Actual behavior The channel promise succeeds. ### Steps to reproduce $ git clone https://github.com/s-gheldd/netty-reproducer.git $ cd netty-reproducer $ mvn test ### Minimal yet complete reproducer code (or URL to code) https://github.com/s-gheldd/netty-reproducer ### Netty version `4.1.16.Final` (last version that had the expected behavior `4.1.13.Final`) ### JVM version (e.g. `java -version`) java version "1.7.0_80" Java(TM) SE Runtime Environment (build 1.7.0_80-b15) Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode) ### OS version (e.g. `uname -a`) Darwin ghelds-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Mon Oct 2 22:20:08 PDT 2017; root:xnu-3248.71.4~1/RELEASE_X86_64 x86_64
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index 4cd8013ba0a..82fc18657a4 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -794,7 +794,10 @@ private void wrap(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLExcepti return; } else { if (buf.isReadable()) { - pendingUnencryptedWrites.addFirst(buf); + pendingUnencryptedWrites.addFirst(buf, promise); + // When we add the buffer/promise pair back we need to be sure we don't complete the promise + // later in finishWrap. We only complete the promise if the buffer is completely consumed. + promise = null; } else { buf.release(); } @@ -1515,9 +1518,13 @@ private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boo notifyHandshakeFailure(cause); } finally { // Ensure we remove and fail all pending writes in all cases and so release memory quickly. - if (pendingUnencryptedWrites != null) { - pendingUnencryptedWrites.releaseAndFailAll(ctx, cause); - } + releaseAndFailAll(cause); + } + } + + private void releaseAndFailAll(Throwable cause) { + if (pendingUnencryptedWrites != null) { + pendingUnencryptedWrites.releaseAndFailAll(ctx, cause); } } @@ -1701,7 +1708,11 @@ public void run() { if (promise.isDone()) { return; } - notifyHandshakeFailure(HANDSHAKE_TIMED_OUT); + try { + notifyHandshakeFailure(HANDSHAKE_TIMED_OUT); + } finally { + releaseAndFailAll(HANDSHAKE_TIMED_OUT); + } } }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS); diff --git a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java index 414847e894f..de9839fa61e 100644 --- a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java +++ b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java @@ -50,10 +50,11 @@ protected AbstractCoalescingBufferQueue(Channel channel, int initSize) { /** * Add a buffer to the front of the queue. */ - public final void addFirst(ByteBuf buf) { + public final void addFirst(ByteBuf buf, ChannelPromise promise) { // Listener would be added here, but since it is null there is no need. The assumption is there is already a // listener at the front of the queue, or there is a buffer at the front of the queue, which was spliced from // buf via remove(). + bufAndListenerPairs.addFirst(new DelegatingChannelPromiseNotifier(promise)); bufAndListenerPairs.addFirst(buf); incrementReadableBytes(buf.readableBytes());
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java index 1e78a6e47dd..0afe89ccf73 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -30,6 +30,7 @@ import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.embedded.EmbeddedChannel; @@ -57,6 +58,7 @@ import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.BlockingQueue; @@ -185,6 +187,22 @@ public void testNonByteBufNotPassThrough() throws Exception { } } + @Test + public void testIncompleteWriteDoesNotCompletePromisePrematurely() throws NoSuchAlgorithmException { + SSLEngine engine = SSLContext.getDefault().createSSLEngine(); + engine.setUseClientMode(false); + + EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine)); + + ChannelPromise promise = ch.newPromise(); + ByteBuf buf = Unpooled.buffer(10).writeZero(10); + ch.writeAndFlush(buf, promise); + assertFalse(promise.isDone()); + assertTrue(ch.finishAndReleaseAll()); + assertTrue(promise.isDone()); + assertThat(promise.cause(), is(instanceOf(SSLException.class))); + } + @Test public void testReleaseSslEngine() throws Exception { assumeTrue(OpenSsl.isAvailable());
test
train
"2017-11-07T06:58:16"
"2017-11-07T13:49:34Z"
sauroter
val
netty/netty/7393_7395
netty/netty
netty/netty/7393
netty/netty/7395
[ "timestamp(timedelta=48330.0, similarity=0.8428181346150718)" ]
188ea59c9d5be75ee0879c114a20e6b633e3714b
a8205e480ee752d6a0fabe222ab96221341cd94b
[ "I think changing copy() to create pooled buffers would be api breaking and would cause memory leaks in user apps...(no need to call .release() right now)\r\nPersonally I avoid using copy() for the reason you mentioned and replace it with:\r\n1. create new pooled buffer with the same size\r\n2. newBuf.readBytes(buf)", "I would also recommend avoiding CompositeByteBuf for most use cases, especially for high performance", "@ninja- I disagree with your point about API breakage. You are supposed to call release() if you not do its a bug. That said I will need to have a look whats going on here.", "@las1991 please check https://github.com/netty/netty/pull/7395 ... This should fix it", "@normanmaurer thank you" ]
[ "Maybe `allocBuffer(length)`?", "@fenik17 good catch... let me do this and add one more assert in the tests 👍 " ]
"2017-11-09T16:51:30Z"
[ "improvement" ]
pooled ByteBuf copy will create unpooled ByteBuf
-Dio.netty.allocator.type : pooled When i call CompositeByteBuf.copy , but it create a Unpooled ByteBuf. and then my server frequently GC. I think this method should be written like this : `public ByteBuf copy(int index, int length) {` `checkIndex(index, length);` `ByteBuf dst = ByteBufAllocator.DEFAULT.buffer(length);` `if (length != 0) {` `copyTo(index, length, toComponentIndex(index), dst);` `}` `return dst;` ` }` This is just one of my Suggestions, if right, hope to fix it later. If not, please correct it.
[ "buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java", "buffer/src/test/java/io/netty/buffer/ConsolidationTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java b/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java index da4876d837b..8a3681b5305 100644 --- a/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/CompositeByteBuf.java @@ -1333,7 +1333,7 @@ public int setBytes(int index, FileChannel in, long position, int length) throws @Override public ByteBuf copy(int index, int length) { checkIndex(index, length); - ByteBuf dst = Unpooled.buffer(length); + ByteBuf dst = allocBuffer(length); if (length != 0) { copyTo(index, length, toComponentIndex(index), dst); }
diff --git a/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java b/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java index 0d3b5db3c9d..f51475bf9ae 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java @@ -1116,4 +1116,24 @@ public void testReleasesItsComponents() { assertEquals(0, buffer.refCnt()); } + @Test + public void testAllocatorIsSameWhenCopy() { + testAllocatorIsSameWhenCopy(false); + } + + @Test + public void testAllocatorIsSameWhenCopyUsingIndexAndLength() { + testAllocatorIsSameWhenCopy(true); + } + + private void testAllocatorIsSameWhenCopy(boolean withIndexAndLength) { + ByteBuf buffer = newBuffer(8); + buffer.writeZero(4); + ByteBuf copy = withIndexAndLength ? buffer.copy(0, 4) : buffer.copy(); + assertEquals(buffer, copy); + assertEquals(buffer.isDirect(), copy.isDirect()); + assertSame(buffer.alloc(), copy.alloc()); + buffer.release(); + copy.release(); + } } diff --git a/buffer/src/test/java/io/netty/buffer/ConsolidationTest.java b/buffer/src/test/java/io/netty/buffer/ConsolidationTest.java index dcbccacb669..e8dcec21020 100644 --- a/buffer/src/test/java/io/netty/buffer/ConsolidationTest.java +++ b/buffer/src/test/java/io/netty/buffer/ConsolidationTest.java @@ -15,6 +15,7 @@ */ package io.netty.buffer; +import io.netty.util.CharsetUtil; import org.junit.Test; import static io.netty.buffer.Unpooled.*; @@ -26,11 +27,13 @@ public class ConsolidationTest { @Test public void shouldWrapInSequence() { - ByteBuf currentBuffer = wrappedBuffer(wrappedBuffer("a".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("1".getBytes()), wrappedBuffer("&".getBytes())); + ByteBuf currentBuffer = wrappedBuffer(wrappedBuffer("a".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("1".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); ByteBuf copy = currentBuffer.copy(); - String s = new String(copy.array()); + String s = copy.toString(CharsetUtil.US_ASCII); assertEquals("a=1&", s); currentBuffer.release(); @@ -39,23 +42,33 @@ public void shouldWrapInSequence() { @Test public void shouldConsolidationInSequence() { - ByteBuf currentBuffer = wrappedBuffer(wrappedBuffer("a".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("1".getBytes()), wrappedBuffer("&".getBytes())); + ByteBuf currentBuffer = wrappedBuffer(wrappedBuffer("a".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("1".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("b".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("2".getBytes()), wrappedBuffer("&".getBytes())); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("b".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("2".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("c".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("3".getBytes()), wrappedBuffer("&".getBytes())); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("c".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("3".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("d".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("4".getBytes()), wrappedBuffer("&".getBytes())); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("d".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("4".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("e".getBytes()), wrappedBuffer("=".getBytes())); - currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("5".getBytes()), wrappedBuffer("&".getBytes())); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("e".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("=".getBytes(CharsetUtil.US_ASCII))); + currentBuffer = wrappedBuffer(currentBuffer, wrappedBuffer("5".getBytes(CharsetUtil.US_ASCII)), + wrappedBuffer("&".getBytes(CharsetUtil.US_ASCII))); ByteBuf copy = currentBuffer.copy(); - String s = new String(copy.array()); + String s = copy.toString(CharsetUtil.US_ASCII); assertEquals("a=1&b=2&c=3&d=4&e=5&", s); currentBuffer.release();
test
val
"2017-11-08T23:36:53"
"2017-11-09T09:24:34Z"
las1991
val
netty/netty/7355_7399
netty/netty
netty/netty/7355
netty/netty/7399
[ "timestamp(timedelta=35.0, similarity=0.852190933309667)" ]
f115bf50cbda70964130236a09fd3045f1b250be
4a4f4ab0cdb403beda217d3d972c79da550aacee
[ "@mosesn sounds right... want to do a PR against `HttpConversionUtil.toHttp2Headers ` ", "we could enhance the conversion to extract out the `trailers` value from the `TE` header instead of just throwing. +1 for a PR.", "I made a PR that extracted the trailers value and also cleaned up the behavior around \"connection\", which I think was wrong. https://github.com/netty/netty/pull/7399", "Fixed by https://github.com/netty/netty/pull/7399" ]
[ "should we use the constructor that takes the `arraySizeHint` based on `values.size()` ?", "consider using an \"old for\" loop if the List implements `RandomAccess` to reduce GC pressure (as the foreach thingy you use here will always create an Iterator)", "While it creates an iterator, it can be allocated on the stack. (Whether it _actually_ is allocated on the stack is a different discussion.)", "Don't you need also need to split value on `,` and trim whitespace?", "@ejona86 we saw GC issues caused by this in the past so better safe then sorry ;)", "looks like it's a linked list: https://github.com/netty/netty/blob/4.1/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java#L163", "Do we need to worry about trimming this? HTTP parsers will generally naturally remove whitespace (but aren't guaranteed to), but that doesn't happen in HTTP/2 (from what I've seen; maybe Netty does).", "It doesn't seem like this should be special-cased or that all empty strings should be handled (by ignoring them), assuming that's its purpose.\r\n\r\nFrom what I can tell, it is only possible for `start == lowerCased.length()` which is \"safe\" for `subSequence()`. That would happen for a string like \"trailing,comma,\" which produces an extra empty string. But if we're concerned about that, then it seems \",leading,comma\" and \"inner,,comma\" should also be disallowed.\r\n\r\nWhile RFC 7230 §7 says:\r\n> In any production that uses the list construct, a sender MUST NOT\r\n generate empty list elements.\r\n\r\nIt also says:\r\n> For compatibility with legacy list rules, a recipient MUST parse and\r\n ignore a reasonable number of empty list elements\r\n\r\nYou may consider using `StringUtil.unescapeCsvFields` for this. It supports quotes, which is unnecessary here, but shouldn't hurt anything other than performance.", ":( It seems `StringUtil.unescapeCsvFields` doesn't do the trimming, even though it is used by `CombinedHttpHeaders`.", "Can we remove this allocation?", "@imasahiro if you think we can easily please submit a PR :) Happy to review and merge", "Isn't this a trash line? As in it does nothing? It doesn't seem like the object is used.", "lol doh! ... I totally missed it. Removed in 78522cf3f0", "@normanmaurer Ah, you already pushed the comment! Thanks anyways :-)", "oh whoops, sorry!" ]
"2017-11-10T22:13:37Z"
[ "defect" ]
HttpConversionUtil.toHttp2Headers should strip http/2 incompatible headers
### Expected behavior When servers receive an h2c upgrade request, it's an http/1.1 message, and it quickly gets turned into an h2c message. ### Actual behavior If the upgrade request has illegal headers, like `te: deflate,gzip;q=0.3` then it doesn't handle it gracefully and throws an exception. ``` W 1030 21:49:47.059 THREAD175 com.twitter.finagle.netty4.channel.ChannelExceptionHandler.exceptionCaught: Unhandled exception in connection with /10.56.221.119:54149, shutting down connection java.lang.IllegalArgumentException: Invalid value for te: deflate,gzip;q=0.3 at io.netty.handler.codec.http2.HttpConversionUtil.toHttp2Headers(HttpConversionUtil.java:423) at io.netty.handler.codec.http2.HttpConversionUtil.toHttp2Headers(HttpConversionUtil.java:399) at io.netty.handler.codec.http2.InboundHttpToHttp2Adapter.handle(InboundHttpToHttp2Adapter.java:61) at io.netty.handler.codec.http2.Http2FrameCodec.userEventTriggered(Http2FrameCodec.java:250) at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:329) at io.netty.channel.AbstractChannelHandlerContext.invokeUserEventTriggered(AbstractChannelHandlerContext.java:315) at io.netty.channel.AbstractChannelHandlerContext.fireUserEventTriggered(AbstractChannelHandlerContext.java:307) at io.netty.handler.codec.http.HttpServerUpgradeHandler$1.operationComplete(HttpServerUpgradeHandler.java:329) at io.netty.handler.codec.http.HttpServerUpgradeHandler$1.operationComplete(HttpServerUpgradeHandler.java:318) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) at io.netty.util.concurrent.DefaultPromise.addListener(DefaultPromise.java:163) at io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:93) at io.netty.channel.DefaultChannelPromise.addListener(DefaultChannelPromise.java:28) at io.netty.handler.codec.http.HttpServerUpgradeHandler.upgrade(HttpServerUpgradeHandler.java:318) at io.netty.handler.codec.http.HttpServerUpgradeHandler.decode(HttpServerUpgradeHandler.java:239) at io.netty.handler.codec.http.HttpServerUpgradeHandler.decode(HttpServerUpgradeHandler.java:40) at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:88) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:310) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:284) at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) at com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:106) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe$1.run(AbstractEpollChannel.java:412) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403) at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:309) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) at java.lang.Thread.run(Thread.java:748) ``` ### Steps to reproduce Send an h2c upgrade request to a server that has illegal h2c headers (like `te: deflate,gzip;q=0.3`). ### Minimal yet complete reproducer code (or URL to code) Haven't had a chance to repro ### Netty version 4.1.16.Final ### JVM version (e.g. `java -version`) jdk8 ### OS version (e.g. `uname -a`) Darwin tw-mbp13-mnakamura.local 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64 ### workaround I haven't found a workaround for this, so it would be lovely if you had any ideas here. I think it just needs to be fixed in netty. Here's what we normally do in finagle: https://github.com/twitter/finagle/blob/develop/finagle-http2/src/main/scala/com/twitter/finagle/http2/transport/RichHttp2ServerDowngrader.scala#L10-L20
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java", "common/src/main/java/io/netty/util/AsciiString.java", "common/src/main/java/io/netty/util/ByteProcessor.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java", "common/src/main/java/io/netty/util/AsciiString.java", "common/src/main/java/io/netty/util/ByteProcessor.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HttpConversionUtilTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java index 03e338fad45..71932fdd808 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HttpConversionUtil.java @@ -15,6 +15,7 @@ package io.netty.handler.codec.http2; import io.netty.buffer.ByteBufAllocator; +import io.netty.handler.codec.UnsupportedValueConverter; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpRequest; @@ -37,7 +38,9 @@ import java.net.URI; import java.util.Iterator; +import java.util.List; import java.util.Map.Entry; +import java.util.Set; import static io.netty.handler.codec.http.HttpScheme.HTTP; import static io.netty.handler.codec.http.HttpScheme.HTTPS; @@ -47,6 +50,7 @@ import static io.netty.handler.codec.http2.Http2Exception.connectionError; import static io.netty.handler.codec.http2.Http2Exception.streamError; import static io.netty.util.AsciiString.EMPTY_STRING; +import static io.netty.util.ByteProcessor.FIND_COMMA; import static io.netty.util.ByteProcessor.FIND_SEMI_COLON; import static io.netty.util.internal.ObjectUtil.checkNotNull; import static io.netty.util.internal.StringUtil.isNullOrEmpty; @@ -410,19 +414,52 @@ public static Http2Headers toHttp2Headers(HttpHeaders inHeaders, boolean validat return out; } + private static CharSequenceMap<AsciiString> toLowercaseMap(List<String> values) { + UnsupportedValueConverter<AsciiString> valueConverter = UnsupportedValueConverter.<AsciiString>instance(); + CharSequenceMap<AsciiString> result = + new CharSequenceMap<AsciiString>(true, valueConverter, values.size()); + + // we iterate because the underlying list is probably a linked list + for (CharSequence value : values) { + AsciiString lowerCased = AsciiString.of(value).toLowerCase(); + try { + int index = lowerCased.forEachByte(FIND_COMMA); + if (index != -1) { + int start = 0; + do { + result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); + start = index + 1; + } while (start < lowerCased.length() && + (index = lowerCased.forEachByte(start, value.length() - start, FIND_COMMA)) != -1); + result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); + } else { + result.add(lowerCased.trim(), EMPTY_STRING); + } + } catch (Exception e) { + // This is not expect to happen because FIND_COMMA never throws but must be caught + // because of the ByteProcessor interface. + throw new IllegalStateException(e); + } + } + return result; + } + public static void toHttp2Headers(HttpHeaders inHeaders, Http2Headers out) { Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence(); + new CharSequenceMap<AsciiString>(); + CharSequenceMap<AsciiString> connectionBlacklist = + toLowercaseMap(inHeaders.getAll(HttpHeaderNames.CONNECTION)); while (iter.hasNext()) { Entry<CharSequence, CharSequence> entry = iter.next(); final AsciiString aName = AsciiString.of(entry.getKey()).toLowerCase(); - if (!HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName)) { + if (!HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) && + !connectionBlacklist.contains(aName)) { // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE - if (aName.contentEqualsIgnoreCase(HttpHeaderNames.TE) && - !AsciiString.contentEqualsIgnoreCase(entry.getValue(), HttpHeaderValues.TRAILERS)) { - throw new IllegalArgumentException("Invalid value for " + HttpHeaderNames.TE + ": " + - entry.getValue()); - } - if (aName.contentEqualsIgnoreCase(HttpHeaderNames.COOKIE)) { + if (aName.contentEqualsIgnoreCase(HttpHeaderNames.TE)) { + if (AsciiString.containsIgnoreCase(entry.getValue(), HttpHeaderValues.TRAILERS)) { + out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS); + } + } else if (aName.contentEqualsIgnoreCase(HttpHeaderNames.COOKIE)) { AsciiString value = AsciiString.of(entry.getValue()); // split up cookies to allow for better compression // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 diff --git a/common/src/main/java/io/netty/util/AsciiString.java b/common/src/main/java/io/netty/util/AsciiString.java index 17e6e5e533b..396fdae2dde 100644 --- a/common/src/main/java/io/netty/util/AsciiString.java +++ b/common/src/main/java/io/netty/util/AsciiString.java @@ -1006,7 +1006,8 @@ public AsciiString toUpperCase() { } /** - * Copies this string removing white space characters from the beginning and end of the string. + * Duplicates this string removing white space characters from the beginning and end of the + * string, without copying. * * @return a new string with characters {@code <= \\u0020} removed from the beginning and the end. */ diff --git a/common/src/main/java/io/netty/util/ByteProcessor.java b/common/src/main/java/io/netty/util/ByteProcessor.java index dcf7f00a4f4..1ca1e58d7ef 100644 --- a/common/src/main/java/io/netty/util/ByteProcessor.java +++ b/common/src/main/java/io/netty/util/ByteProcessor.java @@ -81,10 +81,15 @@ public boolean process(byte value) { ByteProcessor FIND_NON_LF = new IndexNotOfProcessor((byte) '\n'); /** - * Aborts on a {@code CR (';')}. + * Aborts on a semicolon {@code (';')}. */ ByteProcessor FIND_SEMI_COLON = new IndexOfProcessor((byte) ';'); + /** + * Aborts on a comma {@code (',')}. + */ + ByteProcessor FIND_COMMA = new IndexOfProcessor((byte) ','); + /** * Aborts on a {@code CR ('\r')} or a {@code LF ('\n')}. */
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpConversionUtilTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpConversionUtilTest.java index 98e563ee45e..8b665930f6c 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpConversionUtilTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HttpConversionUtilTest.java @@ -15,6 +15,10 @@ */ package io.netty.handler.codec.http2; +import io.netty.handler.codec.http.DefaultHttpHeaders; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.util.AsciiString; import org.junit.Test; @@ -55,4 +59,46 @@ public void setHttp2AuthorityNullOrEmpty() { public void setHttp2AuthorityWithEmptyAuthority() { HttpConversionUtil.setHttp2Authority("info@", new DefaultHttp2Headers()); } + + @Test + public void stripTEHeaders() { + HttpHeaders inHeaders = new DefaultHttpHeaders(); + inHeaders.add(HttpHeaderNames.TE, HttpHeaderValues.GZIP); + Http2Headers out = new DefaultHttp2Headers(); + HttpConversionUtil.toHttp2Headers(inHeaders, out); + assertTrue(out.isEmpty()); + } + + @Test + public void stripTEHeadersExcludingTrailers() { + HttpHeaders inHeaders = new DefaultHttpHeaders(); + inHeaders.add(HttpHeaderNames.TE, HttpHeaderValues.GZIP); + inHeaders.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS); + Http2Headers out = new DefaultHttp2Headers(); + HttpConversionUtil.toHttp2Headers(inHeaders, out); + assertSame(HttpHeaderValues.TRAILERS, out.get(HttpHeaderNames.TE)); + } + + @Test + public void stripConnectionHeadersAndNominees() { + HttpHeaders inHeaders = new DefaultHttpHeaders(); + inHeaders.add(HttpHeaderNames.CONNECTION, "foo"); + inHeaders.add("foo", "bar"); + Http2Headers out = new DefaultHttp2Headers(); + HttpConversionUtil.toHttp2Headers(inHeaders, out); + assertTrue(out.isEmpty()); + } + + @Test + public void stripConnectionNomineesWithCsv() { + HttpHeaders inHeaders = new DefaultHttpHeaders(); + inHeaders.add(HttpHeaderNames.CONNECTION, "foo, bar"); + inHeaders.add("foo", "baz"); + inHeaders.add("bar", "qux"); + inHeaders.add("hello", "world"); + Http2Headers out = new DefaultHttp2Headers(); + HttpConversionUtil.toHttp2Headers(inHeaders, out); + assertEquals(1, out.size()); + assertSame("world", out.get("hello")); + } }
train
val
"2017-11-16T14:07:54"
"2017-10-31T20:33:41Z"
mosesn
val
netty/netty/7365_7402
netty/netty
netty/netty/7365
netty/netty/7402
[ "timestamp(timedelta=22.0, similarity=0.9999999999999999)" ]
010dbe3c734aff7b400c7be8666e5f0c055fca62
b47fb817991b42ec8808c7d26538f3f2464e1fa6
[ "will have a look. Most likely its an overflow.", "@zyclonite please check https://github.com/netty/netty/pull/7402", "thank you for the fast fix!\r\nworks for linux so far (will test it for osx in the evening)\r\n\r\ntypo or on purpose? ```static final long MAX_SCHEDULED_DAYS = 356 * 3;```", "works on osx as well and shows consistent behaviour", "fixed by https://github.com/netty/netty/pull/7402" ]
[ "please note that I used this as it seems to work on linux / Windows and macOS.", "Why do we care about windows and linux here? This is in the kqueue transport.", "add a comment explaining where this number comes from.", "https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2#end\r\n\r\n> The timeout value is limited to 24\thours; longer timeouts will be\r\n silently reinterpreted as 24 hours.\r\n\r\nDo we need to do anything for kqueue? IIRC we verified that scheduled tasks are actually expired even if we are woken up as a result of timeout.", "Is this limit defined in the docs, or is this just based upon the size of the data types? If its data type based this may not be correct and depends upon the type widths. For example `long` may be unsigned 32, but IIRC it is only guaranteed to be smaller than `int`. `time_t` maybe 32 or 64 byte signed integer. If this is based upon datatypes we should get this information via JNI ... hopefully in a limits file somewhere?\r\n\r\nmake this a java doc comment?", "its defined in the manpage to be the max you can set.", "will do... It came from testing ;)", "> EINVAL new_value is not properly initialized (one of the tv_nsec\r\n falls outside the range zero to 999,999,999).\r\n\r\nGotcha ... consider adding to javadocs.", "`TimeUnit.NANOSECONDS.toSeconds(999999999)`\r\n\r\nThat evaluates to zero. Is this calculation correct?", "we can just remove the `TimeUnit.NANOSECONDS.toSeconds(999999999)` here and keep it simple. Will do", "@Scottmitch sorry this was confusing. I tested the value with NIO on linux, windows and macOs ;)", "@Scottmitch oh my ... This is a nice \"bug\". I wonder if this is still true and why they not just fixed it... any idea ?", "So if the variable is named `MAX_SCHEDULED_DAYS` why are there no \"day\" like constants in the arithmetic? It's kind of odd to put a \"seconds\" value into a \"days\" variable.", "carl because I am stupid... I forgot to push the latest change :(", "s/356/365/ ?" ]
"2017-11-13T12:27:26Z"
[ "defect" ]
EventLoop.schedule with big delay fails
this behaviour was discovered by accident, so there is no actual usecase behind it but it is definitely not possible to use Long.MAX_VALUE in milliseconds for a scheduled event ### Expected behavior runnable should trigger after given delay getting a proper exception if something goes wrong ### Actual behavior working with delays smaller of around 10_000_000_000ms on all platforms i tested with (osx, linux) failing on osx with already a delay of 15_768_000_000ms (5 years) with the following exception ``` Nov 04, 2017 2:08:39 PM io.netty.channel.nio.NioEventLoop handleLoopException WARNING: Unexpected exception in the selector loop. java.io.IOException: Invalid argument at sun.nio.ch.KQueueArrayWrapper.kevent0(Native Method) at sun.nio.ch.KQueueArrayWrapper.poll(KQueueArrayWrapper.java:198) at sun.nio.ch.KQueueSelectorImpl.doSelect(KQueueSelectorImpl.java:117) at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86) at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97) at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:746) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:391) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144) at java.lang.Thread.run(Thread.java:748) ``` failing on linux with around 946_080_000_000 (300 years) which immediately triggers the runnable without exception ### Minimal yet complete reproducer code (or URL to code) ``` public class Main { public static void main(String[] args) { final ThreadFactory threadFactory = new DefaultThreadFactory("test-eventloop"); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(1, threadFactory); eventLoopGroup.setIoRatio(50); EventLoop el = eventLoopGroup.next(); Runnable toRun = Main::handle; Future<?> future = el.schedule(toRun, 1000L * 60 * 60 * 24 * 365 * 300, TimeUnit.MILLISECONDS); System.out.println("timer scheduled"); } private static void handle() { System.out.println("timer fired"); } } ``` ### Netty version seems to happen on all 4.1.x versions (tested on 4.1.8, 4.1.15, 4.1.16) ### JVM version (e.g. `java -version`) osx oracle 1.8.0_152 linux openjdk 1.8.0_144 ### OS version (e.g. `uname -a`) darwin 16.7.0 linux 4.13.9 and 4.13.11
[ "common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java", "transport/src/main/java/io/netty/channel/nio/NioEventLoop.java" ]
[ "common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java", "transport/src/main/java/io/netty/channel/nio/NioEventLoop.java" ]
[ "transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java", "transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java", "transport/src/test/java/io/netty/channel/nio/NioEventLoopTest.java" ]
diff --git a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java index 3043b1709fe..795aeba907c 100644 --- a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java @@ -150,6 +150,8 @@ public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) if (delay < 0) { delay = 0; } + validateScheduled(delay, unit); + return schedule(new ScheduledFutureTask<Void>( this, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); } @@ -161,6 +163,8 @@ public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUni if (delay < 0) { delay = 0; } + validateScheduled(delay, unit); + return schedule(new ScheduledFutureTask<V>( this, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); } @@ -177,6 +181,8 @@ public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDela throw new IllegalArgumentException( String.format("period: %d (expected: > 0)", period)); } + validateScheduled(initialDelay, unit); + validateScheduled(period, unit); return schedule(new ScheduledFutureTask<Void>( this, Executors.<Void>callable(command, null), @@ -196,11 +202,21 @@ public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialD String.format("delay: %d (expected: > 0)", delay)); } + validateScheduled(initialDelay, unit); + validateScheduled(delay, unit); + return schedule(new ScheduledFutureTask<Void>( this, Executors.<Void>callable(command, null), ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay))); } + /** + * Sub-classes may override this to restrict the maximal amount of time someone can use to schedule a task. + */ + protected void validateScheduled(long amount, TimeUnit unit) { + // NOOP + } + <V> ScheduledFuture<V> schedule(final ScheduledFutureTask<V> task) { if (inEventLoop()) { scheduledTaskQueue().add(task); diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java index b7d02283e79..cf55ef67ec5 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java @@ -37,6 +37,7 @@ import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import static java.lang.Math.min; @@ -78,6 +79,9 @@ public Integer call() throws Exception { private volatile int wakenUp; private volatile int ioRatio = 50; + // See http://man7.org/linux/man-pages/man2/timerfd_create.2.html. + static final long MAX_SCHEDULED_DAYS = TimeUnit.SECONDS.toDays(999999999); + EpollEventLoop(EventLoopGroup parent, Executor executor, int maxEvents, SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) { super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler); @@ -449,4 +453,12 @@ protected void cleanup() { events.free(); } } + + @Override + protected void validateScheduled(long amount, TimeUnit unit) { + long days = unit.toDays(amount); + if (days > MAX_SCHEDULED_DAYS) { + throw new IllegalArgumentException("days: " + days + " (expected: < " + MAX_SCHEDULED_DAYS + ')'); + } + } } diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java index 5af59ba912c..3badcea96c7 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/KQueueEventLoop.java @@ -33,6 +33,7 @@ import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import static io.netty.channel.kqueue.KQueueEventArray.deleteGlobalRefs; @@ -76,6 +77,8 @@ public Integer call() throws Exception { private volatile int wakenUp; private volatile int ioRatio = 50; + static final long MAX_SCHEDULED_DAYS = 365 * 3; + KQueueEventLoop(EventLoopGroup parent, Executor executor, int maxEvents, SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) { super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler); @@ -367,4 +370,12 @@ private static void handleLoopException(Throwable t) { // Ignore. } } + + @Override + protected void validateScheduled(long amount, TimeUnit unit) { + long days = unit.toDays(amount); + if (days > MAX_SCHEDULED_DAYS) { + throw new IllegalArgumentException("days: " + days + " (expected: < " + MAX_SCHEDULED_DAYS + ')'); + } + } } diff --git a/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java b/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java index c4434cf448b..b1e96e74973 100644 --- a/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java +++ b/transport/src/main/java/io/netty/channel/nio/NioEventLoop.java @@ -113,6 +113,8 @@ public Void run() { } } + static final long MAX_SCHEDULED_DAYS = 365 * 3; + /** * The NIO {@link Selector}. */ @@ -730,6 +732,7 @@ private void select(boolean oldWakenUp) throws IOException { int selectCnt = 0; long currentTimeNanos = System.nanoTime(); long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos); + for (;;) { long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L; if (timeoutMillis <= 0) { @@ -822,4 +825,12 @@ private void selectAgain() { logger.warn("Failed to update SelectionKeys.", t); } } + + @Override + protected void validateScheduled(long amount, TimeUnit unit) { + long days = unit.toDays(amount); + if (days > MAX_SCHEDULED_DAYS) { + throw new IllegalArgumentException("days: " + days + " (expected: < " + MAX_SCHEDULED_DAYS + ')'); + } + } }
diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java new file mode 100644 index 00000000000..0fe824b334d --- /dev/null +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollEventLoopTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.epoll; + +import io.netty.channel.EventLoop; +import io.netty.channel.EventLoopGroup; +import io.netty.util.concurrent.Future; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class EpollEventLoopTest { + + @Test(timeout = 5000L) + public void testScheduleBigDelayOverMax() { + EventLoopGroup group = new EpollEventLoopGroup(1); + + final EventLoop el = group.next(); + try { + el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, Integer.MAX_VALUE, TimeUnit.DAYS); + fail(); + } catch (IllegalArgumentException expected) { + // expected + } + + group.shutdownGracefully(); + } + + @Test + public void testScheduleBigDelay() { + EventLoopGroup group = new EpollEventLoopGroup(1); + + final EventLoop el = group.next(); + Future<?> future = el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, EpollEventLoop.MAX_SCHEDULED_DAYS, TimeUnit.DAYS); + + assertFalse(future.awaitUninterruptibly(1000)); + assertTrue(future.cancel(true)); + group.shutdownGracefully(); + } +} diff --git a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java new file mode 100644 index 00000000000..c7ad56e37ab --- /dev/null +++ b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueEventLoopTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2017 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.kqueue; + +import io.netty.channel.EventLoop; +import io.netty.channel.EventLoopGroup; +import io.netty.util.concurrent.Future; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class KQueueEventLoopTest { + + @Test(timeout = 5000L) + public void testScheduleBigDelayOverMax() { + EventLoopGroup group = new KQueueEventLoopGroup(1); + + final EventLoop el = group.next(); + try { + el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, Integer.MAX_VALUE, TimeUnit.DAYS); + fail(); + } catch (IllegalArgumentException expected) { + // expected + } + + group.shutdownGracefully(); + } + + @Test + public void testScheduleBigDelay() { + EventLoopGroup group = new KQueueEventLoopGroup(1); + + final EventLoop el = group.next(); + Future<?> future = el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, KQueueEventLoop.MAX_SCHEDULED_DAYS, TimeUnit.DAYS); + + assertFalse(future.awaitUninterruptibly(1000)); + assertTrue(future.cancel(true)); + group.shutdownGracefully(); + } +} diff --git a/transport/src/test/java/io/netty/channel/nio/NioEventLoopTest.java b/transport/src/test/java/io/netty/channel/nio/NioEventLoopTest.java index 583ad858eee..aad29b72036 100644 --- a/transport/src/test/java/io/netty/channel/nio/NioEventLoopTest.java +++ b/transport/src/test/java/io/netty/channel/nio/NioEventLoopTest.java @@ -17,12 +17,15 @@ import io.netty.channel.AbstractEventLoopTest; import io.netty.channel.Channel; +import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.util.concurrent.Future; import org.junit.Test; import java.nio.channels.Selector; +import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; @@ -68,4 +71,40 @@ public void run() { group.shutdownGracefully(); } } + + @Test(timeout = 5000L) + public void testScheduleBigDelayOverMax() { + EventLoopGroup group = new NioEventLoopGroup(1); + final EventLoop el = group.next(); + try { + el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, Integer.MAX_VALUE, TimeUnit.DAYS); + fail(); + } catch (IllegalArgumentException expected) { + // expected + } + + group.shutdownGracefully(); + } + + @Test + public void testScheduleBigDelay() { + EventLoopGroup group = new NioEventLoopGroup(1); + + final EventLoop el = group.next(); + Future<?> future = el.schedule(new Runnable() { + @Override + public void run() { + // NOOP + } + }, NioEventLoop.MAX_SCHEDULED_DAYS, TimeUnit.DAYS); + + assertFalse(future.awaitUninterruptibly(1000)); + assertTrue(future.cancel(true)); + group.shutdownGracefully(); + } }
train
val
"2018-04-24T09:19:01"
"2017-11-04T13:22:29Z"
zyclonite
val
netty/netty/7418_7420
netty/netty
netty/netty/7418
netty/netty/7420
[ "timestamp(timedelta=35.0, similarity=0.8444596576464353)" ]
5ca273814ffde676083751352f9c957a912387b9
7baaf9164f3b8bb3f018cd59ae5964d76caf9f5c
[ "Will have a Look\n\n> Am 18.11.2017 um 23:03 schrieb Piotr Kołaczkowski <notifications@github.com>:\n> \n> Expected behavior\n> \n> Writing DefaultLastContent object with trailing headers sends an empty chunk with trailing headers.\n> \n> Actual behavior\n> \n> Writing DefaultLastContent with trailing headers causes EncoderException:\n> \n> io.netty.handler.codec.EncoderException: HttpServerCodec$HttpServerResponseEncoder must produce at least one message.\n> at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:98) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.CombinedChannelDuplexHandler.write(CombinedChannelDuplexHandler.java:348) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:732) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:724) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:809) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:717) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.handler.logging.LoggingHandler.write(LoggingHandler.java:254) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:732) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush(AbstractChannelHandlerContext.java:795) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:807) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:788) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:824) ~[netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at com.datastax.bdp.fs.rest.util.NettyHttpUtil$.writeAndFlush(NettyHttpUtil.scala:77) ~[dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf]\n> at com.datastax.bdp.fs.rest.server.RestServerHandler$$anonfun$sendResponseBody$2.apply(RestServerHandler.scala:163) [dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf]\n> at com.datastax.bdp.fs.rest.server.RestServerHandler$$anonfun$sendResponseBody$2.apply(RestServerHandler.scala:143) [dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf]\n> at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library-2.10.6.jar:na]\n> at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:399) [netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:464) [netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131) [netty-all-4.0.52.Final.jar:4.0.52.Final]\n> at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]\n> \n> Writing DefaultLastContent with no trailing headers in the same place of code, works as expected - sends an empty last chunk and no exception is thrown.\n> \n> Steps to reproduce\n> \n> Setup a simple HttpServer using HttpServerCodec (without HttpMessageAggregator)\n> When sending a response, enable chunked transfer encoding.\n> writeAndFlush a DefaultLastContent object with trailers:\n> val lastContent = new DefaultLastHttpContent()\n> lastContent.trailingHeaders().add(...., ....)\n> context.writeAndFlush(lastContent)\n> Minimal yet complete reproducer code (or URL to code)\n> \n> Netty version\n> \n> We found the problem after upgrading to 4.0.52.Final\n> Error was not present in 4.0.34.Final.\n> \n> JVM version (e.g. java -version)\n> \n> java version \"1.8.0_144\"\n> Java(TM) SE Runtime Environment (build 1.8.0_144-b01)\n> Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)\n> \n> OS version (e.g. uname -a)\n> \n> Linux p5520 4.14.0-041400rc8-generic #201711052313 SMP Sun Nov 5 23:14:08 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Fixed by \r\n8009c4c" ]
[]
"2017-11-19T08:32:10Z"
[ "defect" ]
Sending DefaultLastContent with trailers causes "io.netty.handler.codec.EncoderException: HttpServerCodec$HttpServerResponseEncoder must produce at least one message."
### Expected behavior Writing `DefaultLastContent` object with trailing headers sends an empty chunk with trailing headers. ### Actual behavior Writing `DefaultLastContent` with trailing headers causes EncoderException: ``` io.netty.handler.codec.EncoderException: HttpServerCodec$HttpServerResponseEncoder must produce at least one message. at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:98) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.CombinedChannelDuplexHandler.write(CombinedChannelDuplexHandler.java:348) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:732) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:724) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:809) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:717) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.handler.logging.LoggingHandler.write(LoggingHandler.java:254) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:732) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush(AbstractChannelHandlerContext.java:795) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:807) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:788) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:824) ~[netty-all-4.0.52.Final.jar:4.0.52.Final] at com.datastax.bdp.fs.rest.util.NettyHttpUtil$.writeAndFlush(NettyHttpUtil.scala:77) ~[dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf] at com.datastax.bdp.fs.rest.server.RestServerHandler$$anonfun$sendResponseBody$2.apply(RestServerHandler.scala:163) [dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf] at com.datastax.bdp.fs.rest.server.RestServerHandler$$anonfun$sendResponseBody$2.apply(RestServerHandler.scala:143) [dse-dsefs-common-5.0.12-cbbffcf.jar:5.0.12-cbbffcf] at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32) [scala-library-2.10.6.jar:na] at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:399) [netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:464) [netty-all-4.0.52.Final.jar:4.0.52.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131) [netty-all-4.0.52.Final.jar:4.0.52.Final] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144] ``` Writing `DefaultLastContent` with no trailing headers in the same place of code, works as expected - sends an empty last chunk and no exception is thrown. ### Steps to reproduce 1. Setup a simple HttpServer using HttpServerCodec (without HttpMessageAggregator) 2. When sending a response, enable chunked transfer encoding. 3. writeAndFlush a DefaultLastContent object with trailers: ``` val lastContent = new DefaultLastHttpContent() lastContent.trailingHeaders().add(...., ....) context.writeAndFlush(lastContent) ``` ### Minimal yet complete reproducer code (or URL to code) ### Netty version We found the problem after upgrading to 4.0.52.Final Error was not present in 4.0.34.Final. ### JVM version (e.g. `java -version`) java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode) ### OS version (e.g. `uname -a`) Linux p5520 4.14.0-041400rc8-generic #201711052313 SMP Sun Nov 5 23:14:08 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java", "codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java index 2bdb6ce78ec..50b3ab76731 100755 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectEncoder.java @@ -206,6 +206,7 @@ private void encodeChunkedContent(ChannelHandlerContext ctx, Object msg, long co buf.writeBytes(CRLF); trailersEncodedSizeAccumulator = TRAILERS_WEIGHT_NEW * padSizeForAccumulation(buf.readableBytes()) + TRAILERS_WEIGHT_HISTORICAL * trailersEncodedSizeAccumulator; + out.add(buf); } } else if (contentLength == 0) { // Need to produce some output otherwise an
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java index 742689f683d..ddcb007c571 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpRequestEncoderTest.java @@ -135,16 +135,26 @@ public void testEmptyBufferShouldPassThrough() throws Exception { } @Test - public void testEmptyContentChunked() throws Exception { - testEmptyContent(true); + public void testEmptyContentsChunked() throws Exception { + testEmptyContents(true, false); } @Test - public void testEmptyContentNotChunked() throws Exception { - testEmptyContent(false); + public void testEmptyContentsChunkedWithTrailers() throws Exception { + testEmptyContents(true, true); } - private void testEmptyContent(boolean chunked) throws Exception { + @Test + public void testEmptyContentsNotChunked() throws Exception { + testEmptyContents(false, false); + } + + @Test + public void testEmptyContentNotsChunkedWithTrailers() throws Exception { + testEmptyContents(false, true); + } + + private void testEmptyContents(boolean chunked, boolean trailers) throws Exception { HttpRequestEncoder encoder = new HttpRequestEncoder(); EmbeddedChannel channel = new EmbeddedChannel(encoder); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/"); @@ -157,7 +167,11 @@ private void testEmptyContent(boolean chunked) throws Exception { assertTrue(channel.writeOutbound(new DefaultHttpContent(contentBuffer))); ByteBuf lastContentBuffer = Unpooled.buffer(); - assertTrue(channel.writeOutbound(new DefaultHttpContent(lastContentBuffer))); + LastHttpContent last = new DefaultLastHttpContent(lastContentBuffer); + if (trailers) { + last.trailingHeaders().set("X-Netty-Test", "true"); + } + assertTrue(channel.writeOutbound(last)); // Ensure we only produce ByteBuf instances. ByteBuf head = (ByteBuf) channel.readOutbound(); diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java index 23557036a3c..41e9ea56eb6 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java @@ -286,4 +286,55 @@ private static void assertEmptyResponse(EmbeddedChannel channel, HttpResponseSta buffer = (ByteBuf) channel.readOutbound(); buffer.release(); } + + @Test + public void testEmptyContentsChunked() throws Exception { + testEmptyContents(true, false); + } + + @Test + public void testEmptyContentsChunkedWithTrailers() throws Exception { + testEmptyContents(true, true); + } + + @Test + public void testEmptyContentsNotChunked() throws Exception { + testEmptyContents(false, false); + } + + @Test + public void testEmptyContentNotsChunkedWithTrailers() throws Exception { + testEmptyContents(false, true); + } + + private void testEmptyContents(boolean chunked, boolean trailers) throws Exception { + HttpResponseEncoder encoder = new HttpResponseEncoder(); + EmbeddedChannel channel = new EmbeddedChannel(encoder); + HttpResponse request = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); + if (chunked) { + HttpHeaders.setTransferEncodingChunked(request); + } + assertTrue(channel.writeOutbound(request)); + + ByteBuf contentBuffer = Unpooled.buffer(); + assertTrue(channel.writeOutbound(new DefaultHttpContent(contentBuffer))); + + ByteBuf lastContentBuffer = Unpooled.buffer(); + LastHttpContent last = new DefaultLastHttpContent(lastContentBuffer); + if (trailers) { + last.trailingHeaders().set("X-Netty-Test", "true"); + } + assertTrue(channel.writeOutbound(last)); + + // Ensure we only produce ByteBuf instances. + ByteBuf head = (ByteBuf) channel.readOutbound(); + assertTrue(head.release()); + + ByteBuf content = (ByteBuf) channel.readOutbound(); + content.release(); + + ByteBuf lastContent = (ByteBuf) channel.readOutbound(); + lastContent.release(); + assertFalse(channel.finish()); + } }
train
val
"2017-11-18T09:07:46"
"2017-11-18T22:03:49Z"
pkolaczk
val
netty/netty/7428_7429
netty/netty
netty/netty/7428
netty/netty/7429
[ "timestamp(timedelta=20.0, similarity=0.9429919324532562)" ]
7f4ade7e7d6f907a30926c54e16abefe88e81a8e
5583da60988f634eadebe35785b1a7cdd04648ba
[ "@mikkokar thanks! Will check", "@mikkokar PTAL https://github.com/netty/netty/pull/7429 ", "Fixed via https://github.com/netty/netty/pull/7429" ]
[ "i think the iterator says you need to call hasNext()?", "@carl-mastrangelo yep this would be more correct... let me do this.", "Why is this not passed in as a String[] ?", "Good point. I guess its because the signature of `public <X> X[] toArray(X[] a)` is generic and it is still shared between both `toArray` methods. However we should be able to avoid forcing the `toString` conversion in the case of the `public Object[] toArray()` method. Also it the creation of a `Object[]` array here may not be correct ... we should consider doing something similar to `AbstractCollection`:\r\n\r\n```java\r\nT[] r = a.length >= size ? a :\r\n (T[])java.lang.reflect.Array\r\n .newInstance(a.getClass().getComponentType(), size);\r\n```", "@Scottmitch I disagree about not doing the string conversion. I think we must do it even if `Object[]` or `CharSequence[]` is passed in as we define it as `Set<String>` which should give the guarantee that only `String` will be stored in there. I will change how we create the Array tho." ]
"2017-11-21T13:19:55Z"
[ "defect" ]
Usage of DefaultHttpHeader.names() outcome may result in java.lang.ArrayStoreException
`DefaultHttpHeader.names()` exposes HTTP header names as a `Set<String>`. Converting the resulting set to an array using `toArray(String[])` throws an exception: `java.lang.ArrayStoreException: io.netty.util.AsciiString`. ### Expected behavior I expect following code to return an array of String objects: ``` Set<String> nettyHeaders = new DefaultHttpHeaders(true) .add(HttpHeaderNames.CONTENT_LENGTH, "50") .names(); String[] namesArray = nettyHeaders.toArray(new String[nettyHeaders.size()]); ``` ### Actual behavior But the code above throws an exception: ``` java.lang.ArrayStoreException: io.netty.util.AsciiString at io.netty.handler.codec.HeadersUtils$DelegatingStringSet.fillArray(HeadersUtils.java:234) at io.netty.handler.codec.HeadersUtils$DelegatingStringSet.toArray(HeadersUtils.java:227) at io.netty.handler.codec.http.DefaultHttpHeadersTest.providesHeaderNamesAsArray(DefaultHttpHeadersTest.java:222) ... ``` ### Steps to reproduce See below. ### Minimal yet complete reproducer code (or URL to code) I have constructed this test to demonstrate the issue: ``` @Test public void providesHeaderNamesAsArray() throws Exception { Set<String> nettyHeaders = new DefaultHttpHeaders(true) .add(HttpHeaderNames.CONTENT_LENGTH, "50") .names(); String[] namesArray = nettyHeaders.toArray(new String[nettyHeaders.size()]); assertArrayEquals(namesArray, new String[]{"content-length"}); } ``` ### Root Cause The problem lies in the DelegatingStringSet class in HeaderUtils.java, which adapts the underlying `CharSequence` to a `String`. Well, the adaptation is implemented for the `iterator()` only, but not for `toArray()` method. ### Netty version 4.1.17 and latest Netty 4.1 branch. ### JVM version (e.g. `java -version`) jdk 1.8.0_131 ### OS version (e.g. `uname -a`)
[ "codec/src/main/java/io/netty/handler/codec/HeadersUtils.java" ]
[ "codec/src/main/java/io/netty/handler/codec/HeadersUtils.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java" ]
diff --git a/codec/src/main/java/io/netty/handler/codec/HeadersUtils.java b/codec/src/main/java/io/netty/handler/codec/HeadersUtils.java index d4062209b38..0582353b765 100644 --- a/codec/src/main/java/io/netty/handler/codec/HeadersUtils.java +++ b/codec/src/main/java/io/netty/handler/codec/HeadersUtils.java @@ -15,6 +15,7 @@ */ package io.netty.handler.codec; +import java.util.AbstractCollection; import java.util.AbstractList; import java.util.Collection; import java.util.Iterator; @@ -84,7 +85,7 @@ public static Set<String> namesAsString(Headers<CharSequence, CharSequence, ?> h private static final class StringEntryIterator implements Iterator<Entry<String, String>> { private final Iterator<Entry<CharSequence, CharSequence>> iter; - public StringEntryIterator(Iterator<Entry<CharSequence, CharSequence>> iter) { + StringEntryIterator(Iterator<Entry<CharSequence, CharSequence>> iter) { this.iter = iter; } @@ -145,7 +146,7 @@ public String toString() { private static final class StringIterator<T> implements Iterator<String> { private final Iterator<T> iter; - public StringIterator(Iterator<T> iter) { + StringIterator(Iterator<T> iter) { this.iter = iter; } @@ -167,7 +168,7 @@ public void remove() { } private static final class CharSequenceDelegatingStringSet extends DelegatingStringSet<CharSequence> { - public CharSequenceDelegatingStringSet(Set<CharSequence> allNames) { + CharSequenceDelegatingStringSet(Set<CharSequence> allNames) { super(allNames); } @@ -182,10 +183,10 @@ public boolean addAll(Collection<? extends String> c) { } } - private abstract static class DelegatingStringSet<T> implements Set<String> { + private abstract static class DelegatingStringSet<T> extends AbstractCollection<String> implements Set<String> { protected final Set<T> allNames; - public DelegatingStringSet(Set<T> allNames) { + DelegatingStringSet(Set<T> allNames) { this.allNames = checkNotNull(allNames, "allNames"); } @@ -209,71 +210,11 @@ public Iterator<String> iterator() { return new StringIterator<T>(allNames.iterator()); } - @Override - public Object[] toArray() { - Object[] arr = new Object[size()]; - fillArray(arr); - return arr; - } - - @SuppressWarnings("unchecked") - @Override - public <X> X[] toArray(X[] a) { - if (a == null || a.length < size()) { - X[] arr = (X[]) new Object[size()]; - fillArray(arr); - return arr; - } - fillArray(a); - return a; - } - - private void fillArray(Object[] arr) { - Iterator<T> itr = allNames.iterator(); - for (int i = 0; i < size(); ++i) { - arr[i] = itr.next(); - } - } - @Override public boolean remove(Object o) { return allNames.remove(o); } - @Override - public boolean containsAll(Collection<?> c) { - for (Object o : c) { - if (!contains(o)) { - return false; - } - } - return true; - } - - @Override - public boolean removeAll(Collection<?> c) { - boolean modified = false; - for (Object o : c) { - if (remove(o)) { - modified = true; - } - } - return modified; - } - - @Override - public boolean retainAll(Collection<?> c) { - boolean modified = false; - Iterator<String> it = iterator(); - while (it.hasNext()) { - if (!c.contains(it.next())) { - it.remove(); - modified = true; - } - } - return modified; - } - @Override public void clear() { allNames.clear();
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java index b09546eeb73..5514f23ff07 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java @@ -23,16 +23,13 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.Set; import static io.netty.handler.codec.http.HttpHeadersTestUtils.of; import static io.netty.util.AsciiString.contentEquals; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class DefaultHttpHeadersTest { private static final CharSequence HEADER_NAME = "testHeader"; @@ -209,6 +206,16 @@ public void setObjectIterable() { assertDefaultValues(headers, HeaderValue.THREE); } + @Test + public void providesHeaderNamesAsArray() throws Exception { + Set<String> nettyHeaders = new DefaultHttpHeaders() + .add(HttpHeaderNames.CONTENT_LENGTH, 10) + .names(); + + String[] namesArray = nettyHeaders.toArray(new String[nettyHeaders.size()]); + assertArrayEquals(namesArray, new String[] { HttpHeaderNames.CONTENT_LENGTH.toString() }); + } + private static void assertDefaultValues(final DefaultHttpHeaders headers, final HeaderValue headerValue) { assertTrue(contentEquals(headerValue.asList().get(0), headers.get(HEADER_NAME))); List<CharSequence> expected = headerValue.asList();
train
val
"2017-11-21T11:55:39"
"2017-11-21T12:43:45Z"
mikkokar
val
netty/netty/7483_7492
netty/netty
netty/netty/7483
netty/netty/7492
[ "timestamp(timedelta=24.0, similarity=0.9999999999999999)" ]
b2bc6407ab6ff6e9be65ada56e4a4058e2c6a293
4f0ec0d83eb63876ef67ad58fcee44a063b6c220
[ "@rvansa looking now", "@rvansa PTAL #7492", "Fixed by https://github.com/netty/netty/pull/7492" ]
[ "`j.u.c.RejectedExecutionHandler` is not limited to throwing REEs, why not `Throwable`?", "We try to not introduce more Throwable catches if we rethrow these. Maybe `Exception` ?", "Sounds good.", "@rvansa PTAL again just pushed", "optional:\r\n\r\n`if (cause instanceof Error)) {`\r\n", "I think I would like to keep it as it is for now just in case someone creates a special `Throwable` sub-type" ]
"2017-12-11T13:38:23Z"
[ "defect" ]
SingleThreadEventExecutor ignores startThread failures
### Expected behavior SingleThreadEventExecutor should throw an exception when it can't start the thread second time. ### Actual behavior When `doStartThread` throws an exception, e.g. due to the actual executor being depleted of threads and throwing in its rejected execution handler, the STEE ends up in started state anyway. If we try to execute another task in this executor, it will be queued but the thread won't be started anymore and the task will linger forever. ### Netty version 4.1.9 ### JVM version (e.g. `java -version`) 1.8
[ "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java" ]
[ "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java" ]
[ "common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java" ]
diff --git a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java index 510d05aea49..d1de03fe6e3 100644 --- a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -16,6 +16,7 @@ package io.netty.util.concurrent; import io.netty.util.internal.ObjectUtil; +import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; @@ -582,7 +583,18 @@ public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit uni gracefulShutdownTimeout = unit.toNanos(timeout); if (oldState == ST_NOT_STARTED) { - doStartThread(); + try { + doStartThread(); + } catch (Throwable cause) { + STATE_UPDATER.set(this, ST_TERMINATED); + terminationFuture.tryFailure(cause); + + if (!(cause instanceof Exception)) { + // Also rethrow as it may be an OOME for example + PlatformDependent.throwException(cause); + } + return terminationFuture; + } } if (wakeup) { @@ -634,7 +646,18 @@ public void shutdown() { } if (oldState == ST_NOT_STARTED) { - doStartThread(); + try { + doStartThread(); + } catch (Throwable cause) { + STATE_UPDATER.set(this, ST_TERMINATED); + terminationFuture.tryFailure(cause); + + if (!(cause instanceof Exception)) { + // Also rethrow as it may be an OOME for example + PlatformDependent.throwException(cause); + } + return; + } } if (wakeup) { @@ -837,7 +860,12 @@ protected final void reject(Runnable task) { private void startThread() { if (state == ST_NOT_STARTED) { if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_STARTED)) { - doStartThread(); + try { + doStartThread(); + } catch (Throwable cause) { + STATE_UPDATER.set(this, ST_NOT_STARTED); + PlatformDependent.throwException(cause); + } } } }
diff --git a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java index 3be7dc8f831..55981b24060 100644 --- a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java @@ -21,6 +21,8 @@ import java.util.Collections; import java.util.Set; import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; @@ -28,6 +30,48 @@ public class SingleThreadEventExecutorTest { + @Test + public void testWrappedExecutureIsShutdown() { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + SingleThreadEventExecutor executor = new SingleThreadEventExecutor(null, executorService, false) { + @Override + protected void run() { + while (!confirmShutdown()) { + Runnable task = takeTask(); + if (task != null) { + task.run(); + } + } + } + }; + + executorService.shutdownNow(); + executeShouldFail(executor); + executeShouldFail(executor); + try { + executor.shutdownGracefully().syncUninterruptibly(); + Assert.fail(); + } catch (RejectedExecutionException expected) { + // expected + } + Assert.assertTrue(executor.isShutdown()); + } + + private static void executeShouldFail(Executor executor) { + try { + executor.execute(new Runnable() { + @Override + public void run() { + // Noop. + } + }); + Assert.fail(); + } catch (RejectedExecutionException expected) { + // expected + } + } + @Test public void testThreadProperties() { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
val
val
"2017-12-08T10:26:15"
"2017-12-07T10:00:53Z"
rvansa
val
netty/netty/5226_7503
netty/netty
netty/netty/5226
netty/netty/7503
[ "timestamp(timedelta=18.0, similarity=0.8450339385731247)" ]
1988cd041d3d5eaa5f52e58d3d3f773b9ef17fe7
443243a7d0c0b3f4ff129211b2f99b66178cf73b
[ "@Scottmitch I will take care.\n", "Fixed by https://github.com/netty/netty/pull/7503" ]
[ "Note this change was needed as we not correctly copied the headers before in our replace(...) methods.", "Also we missed this before :(", "Also we missed this before :(", "`set` will also do `clear` which will do some unnecessary work (array filling, pointer updating, assignments). We should be able to just use `addImpl` instead of `set`.", "nit: consider simplifying this to a tertiary statement:\r\n\r\n```java\r\nreturn (headers instanceof DefaultHttpHeaders) ? ((DefaultHttpHeaders) headers).copy()\r\n : new DefaultHttpHeaders().set(headers);\r\n```", "this class doesn't implement `clone` so should we get rid of the `implements Cloneable`?", "`i nthe` -> `in the`", "`We expect to not have` -> `We do not expect to have`", "@Scottmitch doh.. good catch, thats a left-over as I first wanted to just use `clone()` for it.", "can we just make `copy()` a method of the `HttpHeaders` class because it is an abstract class? Then we don't have to use the static method outside and can just call `.copy()` on the object." ]
"2017-12-13T19:30:21Z"
[]
HttpObjectAggregator.replace headers may enforce validation when they should not
`HttpObjectAggregator.replace` creates a new `DefaultFullHttpRequest` and does not specify a value for the `validateHeaders` during construction. This would mean that header validation is not consistent from the user's perspective and may enforce validation when the user does not want validation ... which may throw unexpected/undesired errors. This issue also exists in other implementations of `replace` in codec-http.
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java", "codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java", "codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java", "codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java", "codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java", "codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java", "codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java index ba55d9657e9..117e6dbf648 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpRequest.java @@ -142,7 +142,10 @@ public FullHttpRequest retainedDuplicate() { @Override public FullHttpRequest replace(ByteBuf content) { - return new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content, headers(), trailingHeaders()); + FullHttpRequest request = new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content, + headers().copy(), trailingHeaders().copy()); + request.setDecoderResult(decoderResult()); + return request; } @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java index 134865cabb5..012b996a240 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultFullHttpResponse.java @@ -149,7 +149,10 @@ public FullHttpResponse retainedDuplicate() { @Override public FullHttpResponse replace(ByteBuf content) { - return new DefaultFullHttpResponse(protocolVersion(), status(), content, headers(), trailingHeaders()); + FullHttpResponse response = new DefaultFullHttpResponse(protocolVersion(), status(), content, + headers().copy(), trailingHeaders().copy()); + response.setDecoderResult(decoderResult()); + return response; } @Override diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java index e8fcf3e7adb..88af27f738e 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpHeaders.java @@ -348,6 +348,11 @@ public int hashCode() { return headers.hashCode(CASE_SENSITIVE_HASHER); } + @Override + public HttpHeaders copy() { + return new DefaultHttpHeaders(headers.copy()); + } + private static void validateHeaderNameElement(byte value) { switch (value) { case 0x00: diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java index 7df00eac2b7..35cfc5c5f18 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java @@ -1693,4 +1693,11 @@ public boolean contains(CharSequence name, CharSequence value, boolean ignoreCas public String toString() { return HeadersUtils.toString(getClass(), iteratorCharSequence(), size()); } + + /** + * Returns a deap copy of the passed in {@link HttpHeaders}. + */ + public HttpHeaders copy() { + return new DefaultHttpHeaders().set(this); + } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java index ace7e4642b4..257581fe232 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpObjectAggregator.java @@ -424,9 +424,8 @@ public FullHttpRequest retainedDuplicate() { @Override public FullHttpRequest replace(ByteBuf content) { - DefaultFullHttpRequest dup = new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content); - dup.headers().set(headers()); - dup.trailingHeaders().set(trailingHeaders()); + DefaultFullHttpRequest dup = new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content, + headers().copy(), trailingHeaders().copy()); dup.setDecoderResult(decoderResult()); return dup; } @@ -523,9 +522,8 @@ public FullHttpResponse retainedDuplicate() { @Override public FullHttpResponse replace(ByteBuf content) { - DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content); - dup.headers().set(headers()); - dup.trailingHeaders().set(trailingHeaders()); + DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content, + headers().copy(), trailingHeaders().copy()); dup.setDecoderResult(decoderResult()); return dup; } diff --git a/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java b/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java index 5664706b987..01b64e85623 100644 --- a/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java +++ b/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java @@ -952,6 +952,16 @@ private T thisT() { return (T) this; } + /** + * Returns a deep copy of this instance. + */ + public DefaultHeaders<K, V, T> copy() { + DefaultHeaders<K, V, T> copy = new DefaultHeaders<K, V, T>( + hashingStrategy, valueConverter, nameValidator, entries.length); + copy.addImpl(this); + return copy; + } + private final class HeaderIterator implements Iterator<Map.Entry<K, V>> { private HeaderEntry<K, V> current = head;
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java index b29c0966d7d..8fb4ebfc678 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/InboundHttp2ToHttpAdapterTest.java @@ -62,6 +62,7 @@ import static io.netty.handler.codec.http2.Http2TestUtil.runInChannel; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -607,6 +608,9 @@ public void run() throws Http2Exception { verify(serverListener, times(2)).messageReceived(requestCaptor.capture()); capturedRequests = requestCaptor.getAllValues(); assertEquals(2, capturedRequests.size()); + // We do not expect to have this header in the captured request so remove it now. + assertNotNull(request.headers().remove("x-http2-stream-weight")); + assertEquals(request, capturedRequests.get(0)); assertEquals(request2, capturedRequests.get(1));
val
val
"2017-12-12T09:08:58"
"2016-05-09T15:27:51Z"
Scottmitch
val
netty/netty/7511_7512
netty/netty
netty/netty/7511
netty/netty/7512
[ "timestamp(timedelta=0.0, similarity=0.8629639334100965)" ]
640a22df9efb41e3d29b79916938c1c315be2872
94ab0dc4425b05e8691c0954f70c1859d0b7294c
[ "@mosesn can you open a PR with a unit test ?", "@normanmaurer yeah, I'll take a look.", "@mosesn thanks buddy", "I still haven't been able to make a unit test, but I have a better idea of what's happening.\r\n\r\nAfter we have already added the name length and value length of the header with the long name length to the headersLength, we can go into \"Literal Header Field with Incremental Indexing\" mode, and then we go to READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX , and if index is not 127 or 0, we go into into the same area as before, because `nameLength` hasn't changed yet." ]
[ "this comment is a bit confusing... when we \"get an exception\" shouldn't we need to catch it ?", "oh, I just copy/pasted this from the previous test. I'll just delete it.", "updated, PTAL" ]
"2017-12-16T02:19:27Z"
[]
double counting header name length in http/2
### Expected behavior A header with a name of length X and a value of length Y gets considered as being length X + Y in total. ### Actual behavior A header with a name of length X and a value of length Y gets considered as being length 2X + Y in total. I think this is where the bug is: https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java#L262 ### Steps to reproduce Use hpack decoder to decode a header. ### Netty version 4.1.16.Final ### JVM version (e.g. `java -version`) jdk8
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java index ce81f7c4984..07b1e30b535 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java @@ -162,6 +162,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers) throws Http2E default: // Index was stored as the prefix name = readName(index); + nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; } } else if ((b & 0x20) == 0x20) { @@ -187,6 +188,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers) throws Http2E default: // Index was stored as the prefix name = readName(index); + nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; } } @@ -205,6 +207,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers) throws Http2E case READ_INDEXED_HEADER_NAME: // Header Name matches an entry in the Header Table name = readName(decodeULE128(in, index)); + nameLength = name.length(); state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; break;
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java index 8dd885400ce..04552b9263e 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java @@ -455,4 +455,26 @@ public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSize in.release(); } } + + @Test + public void testDecodeCountsNamesOnlyOnce() throws Http2Exception { + ByteBuf in = Unpooled.buffer(200); + try { + hpackDecoder.setMaxHeaderListSize(3500, 4000); + HpackEncoder hpackEncoder = new HpackEncoder(true); + + // encode headers that are slightly larger than maxHeaderListSize + // but smaller than maxHeaderListSizeGoAway + Http2Headers toEncode = new DefaultHttp2Headers(); + toEncode.add(String.format("%03000d", 0).replace('0', 'f'), "value"); + toEncode.add("accept", "value"); + hpackEncoder.encodeHeaders(1, in, toEncode, NEVER_SENSITIVE); + + Http2Headers decoded = new DefaultHttp2Headers(); + hpackDecoder.decode(1, in, decoded); + assertEquals(2, decoded.size()); + } finally { + in.release(); + } + } }
train
val
"2017-12-15T21:21:18"
"2017-12-15T17:17:05Z"
mosesn
val
netty/netty/7509_7523
netty/netty
netty/netty/7509
netty/netty/7523
[ "keyword_issue_to_pr", "timestamp(timedelta=67.0, similarity=0.843997554030955)" ]
94ab0dc4425b05e8691c0954f70c1859d0b7294c
144716f668efaa5bf4bb4175ec5513bd4f0f60b7
[ "@durigon just to ensure did you try 4.1.18.Final as well ?", "@normanmaurer #4283 and #4585 are still in process, so it seems that it has not been fixed.\r\n", "I think this will be resolved once https://github.com/netty/netty/issues/4283 is resolved.", "@durigon - Can you run your tests with https://github.com/netty/netty/pull/7523 ?", "@Scottmitch Thank you. I'll test it and share the results.", "As expected, there is no infinite loop. @Scottmitch thanks :)", "thanks for reporting and verifying @durigon!", "Fixed by #7523 " ]
[]
"2017-12-19T03:54:42Z"
[ "defect" ]
HTTP/2 UniformStreamByteDistributor has an infinite loop problem when transferring content that exceeds 2 GB.
### Expected behavior no infinite loop ### Actual behavior HTTP/2 UniformStreamByteDistributor has an infinite loop problem when transferring content that exceeds 2GB. - [Http2CodecUtil streamableBytes - If pendingBytes is out of the integer range, streamableBytes may be zero.](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java#L226) - [Since there is a frame and windowSize is greater than 0, writing 0 bytes is infinitely repeated.](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java#L170) - [UniformStreamByteDistributor StreamState.streamableBytes](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java#L118) - Workaround : Add flow controller so that HTTP/2 stream pending bytes do not exceed the integer(pendingBytes, streamableBytes). ### Steps to reproduce Use curl with limit-rate to request more than 2Gbytes of content In multiple terminal(More than 6 terminals) `curl -v https://localhost/3gbytes.bin -o/dev/null --http2 --insecure --limit-rate 1M ` ### Minimal yet complete reproducer code (or URL to code) ### Netty version netty-4.1.12.Final ### JVM version (e.g. `java -version`) #java -version java version "1.8.0_131" Java(TM) SE Runtime Environment (build 1.8.0_131-b11) ### OS version (e.g. `uname -a`) uname -a Linux sunggonsong 2.6.32-696.13.2.el6.x86_64 #1 SMP Thu Oct 5 21:22:16 UTC 2017 x86_64 x86_64 x86_64 GNU/Linu
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java index 034140c81f8..6e02e7cecf5 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java @@ -16,7 +16,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.StreamByteDistributor.Writer; -import io.netty.util.BooleanSupplier; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -274,7 +273,7 @@ private final class FlowState implements StreamByteDistributor.StreamState { private final Http2Stream stream; private final Deque<FlowControlled> pendingWriteQueue; private int window; - private int pendingBytes; + private long pendingBytes; private boolean markedWritable; /** @@ -285,12 +284,6 @@ private final class FlowState implements StreamByteDistributor.StreamState { * Set to true if cancel() was called. */ private boolean cancelled; - private BooleanSupplier isWritableSupplier = new BooleanSupplier() { - @Override - public boolean get() throws Exception { - return windowSize() > pendingBytes(); - } - }; FlowState(Http2Stream stream) { this.stream = stream; @@ -302,11 +295,7 @@ public boolean get() throws Exception { * @return {@code true} if the stream associated with this object is writable. */ boolean isWritable() { - try { - return isWritableSupplier.get(); - } catch (Throwable cause) { - throw new Error("isWritableSupplier should never throw!", cause); - } + return windowSize() > pendingBytes() && !cancelled; } /** @@ -432,7 +421,7 @@ private int writableWindow() { } @Override - public int pendingBytes() { + public long pendingBytes() { return pendingBytes; } @@ -502,7 +491,6 @@ private void cancel(Throwable cause) { streamByteDistributor.updateStreamableBytes(this); - isWritableSupplier = BooleanSupplier.FALSE_SUPPLIER; monitor.stateCancelled(this); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java index 12bf363abc5..0854b55ccb4 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java @@ -223,7 +223,7 @@ public static void writeFrameHeader(ByteBuf out, int payloadLength, byte type, * Calculate the amount of bytes that can be sent by {@code state}. The lower bound is {@code 0}. */ public static int streamableBytes(StreamByteDistributor.StreamState state) { - return max(0, min(state.pendingBytes(), state.windowSize())); + return max(0, (int) min(state.pendingBytes(), state.windowSize())); } /** diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java index eaf47903ce4..a3127376354 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java @@ -40,7 +40,7 @@ interface StreamState { * @return The amount of bytes this stream has pending to send. * @see Http2CodecUtil#streamableBytes(StreamState) */ - int pendingBytes(); + long pendingBytes(); /** * Indicates whether or not there are frames pending for this stream. diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java index c3e5e2faaa7..421d3488b20 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java @@ -129,13 +129,6 @@ private State state(Http2Stream stream) { return checkNotNull(stream, "stream").getProperty(stateKey); } - /** - * For testing only! - */ - int streamableBytes0(Http2Stream stream) { - return state(stream).streamableBytes; - } - /** * The remote flow control state for a single stream. */ diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java index 9a852a22d8f..b7c2cddf52c 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java @@ -352,13 +352,6 @@ private State state(int streamId) { return stream != null ? state(stream) : stateOnlyMap.get(streamId); } - /** - * For testing only! - */ - int streamableBytes0(Http2Stream stream) { - return state(stream).streamableBytes; - } - /** * For testing only! */
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java index 12b177f975a..bb1e4695abf 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java @@ -14,6 +14,9 @@ */ package io.netty.handler.codec.http2; +import io.netty.handler.codec.http2.Http2TestUtil.TestStreamByteDistributorStreamState; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -21,6 +24,8 @@ abstract class AbstractWeightedFairQueueByteDistributorDependencyTest { Http2Connection connection; WeightedFairQueueByteDistributor distributor; + private IntObjectMap<TestStreamByteDistributorStreamState> stateMap = + new IntObjectHashMap<TestStreamByteDistributorStreamState>(); @Mock StreamByteDistributor.Writer writer; @@ -35,45 +40,30 @@ Answer<Void> writeAnswer(final boolean closeIfNoFrame) { public Void answer(InvocationOnMock in) throws Throwable { Http2Stream stream = in.getArgument(0); int numBytes = in.getArgument(1); - int streamableBytes = distributor.streamableBytes0(stream) - numBytes; - boolean hasFrame = streamableBytes > 0; - updateStream(stream.id(), streamableBytes, hasFrame, hasFrame, closeIfNoFrame); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + state.isWriteAllowed = state.hasFrame; + if (closeIfNoFrame && !state.hasFrame) { + stream.close(); + } + distributor.updateStreamableBytes(state); return null; } }; } - void updateStream(final int streamId, final int streamableBytes, final boolean hasFrame) { - updateStream(streamId, streamableBytes, hasFrame, hasFrame, false); + void initState(final int streamId, final long streamableBytes, final boolean hasFrame) { + initState(streamId, streamableBytes, hasFrame, hasFrame); } - void updateStream(final int streamId, final int pendingBytes, final boolean hasFrame, - final boolean isWriteAllowed, boolean closeIfNoFrame) { + void initState(final int streamId, final long pendingBytes, final boolean hasFrame, + final boolean isWriteAllowed) { final Http2Stream stream = stream(streamId); - if (closeIfNoFrame && !hasFrame) { - stream(streamId).close(); - } - distributor.updateStreamableBytes(new StreamByteDistributor.StreamState() { - @Override - public Http2Stream stream() { - return stream; - } - - @Override - public int pendingBytes() { - return pendingBytes; - } - - @Override - public boolean hasFrame() { - return hasFrame; - } - - @Override - public int windowSize() { - return isWriteAllowed ? pendingBytes : -1; - } - }); + TestStreamByteDistributorStreamState state = new TestStreamByteDistributorStreamState(stream, pendingBytes, + hasFrame, isWriteAllowed); + stateMap.put(streamId, state); + distributor.updateStreamableBytes(state); } void setPriority(int streamId, int parent, int weight, boolean exclusive) throws Http2Exception { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java index 6c0b129f315..8fafd435d8d 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java @@ -35,6 +35,7 @@ import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_LIST_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_TABLE_SIZE; +import static java.lang.Math.min; /** * Utilities for the integration tests. @@ -470,4 +471,39 @@ public void operationComplete(ChannelFuture future) throws Exception { } }; } + + static final class TestStreamByteDistributorStreamState implements StreamByteDistributor.StreamState { + private final Http2Stream stream; + boolean isWriteAllowed; + long pendingBytes; + boolean hasFrame; + + TestStreamByteDistributorStreamState(Http2Stream stream, long pendingBytes, boolean hasFrame, + boolean isWriteAllowed) { + this.stream = stream; + this.isWriteAllowed = isWriteAllowed; + this.pendingBytes = pendingBytes; + this.hasFrame = hasFrame; + } + + @Override + public Http2Stream stream() { + return stream; + } + + @Override + public long pendingBytes() { + return pendingBytes; + } + + @Override + public boolean hasFrame() { + return hasFrame; + } + + @Override + public int windowSize() { + return isWriteAllowed ? (int) min(pendingBytes, Integer.MAX_VALUE) : -1; + } + } } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java index 28d8ba7bb13..c804174b8b4 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java @@ -14,6 +14,9 @@ */ package io.netty.handler.codec.http2; +import io.netty.handler.codec.http2.Http2TestUtil.TestStreamByteDistributorStreamState; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -32,13 +35,13 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.same; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -55,6 +58,7 @@ public class UniformStreamByteDistributorTest { private Http2Connection connection; private UniformStreamByteDistributor distributor; + private IntObjectMap<TestStreamByteDistributorStreamState> stateMap; @Mock private StreamByteDistributor.Writer writer; @@ -63,6 +67,7 @@ public class UniformStreamByteDistributorTest { public void setup() throws Http2Exception { MockitoAnnotations.initMocks(this); + stateMap = new IntObjectHashMap<TestStreamByteDistributorStreamState>(); connection = new DefaultHttp2Connection(false); distributor = new UniformStreamByteDistributor(connection); @@ -83,8 +88,10 @@ private Answer<Void> writeAnswer() { public Void answer(InvocationOnMock in) throws Throwable { Http2Stream stream = in.getArgument(0); int numBytes = in.getArgument(1); - int streamableBytes = distributor.streamableBytes0(stream) - numBytes; - updateStream(stream.id(), streamableBytes, streamableBytes > 0); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + distributor.updateStreamableBytes(state); return null; } }; @@ -97,10 +104,10 @@ private void resetWriter() { @Test public void bytesUnassignedAfterProcessing() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); assertFalse(write(10)); verifyWrite(STREAM_A, 1); @@ -115,10 +122,10 @@ public void bytesUnassignedAfterProcessing() throws Http2Exception { @Test public void connectionErrorForWriterException() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); Exception fakeException = new RuntimeException("Fake exception"); doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3)); @@ -158,10 +165,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { setPriority(STREAM_D, STREAM_A, (short) 100, false); // Update the streams. - updateStream(STREAM_A, CHUNK_SIZE, true); - updateStream(STREAM_B, CHUNK_SIZE, true); - updateStream(STREAM_C, CHUNK_SIZE, true); - updateStream(STREAM_D, CHUNK_SIZE, true); + initState(STREAM_A, CHUNK_SIZE, true); + initState(STREAM_B, CHUNK_SIZE, true); + initState(STREAM_C, CHUNK_SIZE, true); + initState(STREAM_D, CHUNK_SIZE, true); // Only write 3 * chunkSize, so that we'll only write to the first 3 streams. int written = 3 * CHUNK_SIZE; @@ -182,7 +189,7 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { @Test public void streamWithMoreDataShouldBeEnqueuedAfterWrite() throws Http2Exception { // Give the stream a bunch of data. - updateStream(STREAM_A, 2 * CHUNK_SIZE, true); + initState(STREAM_A, 2 * CHUNK_SIZE, true); // Write only part of the data. assertTrue(write(CHUNK_SIZE)); @@ -199,10 +206,10 @@ public void streamWithMoreDataShouldBeEnqueuedAfterWrite() throws Http2Exception @Test public void emptyFrameAtHeadIsWritten() throws Http2Exception { - updateStream(STREAM_A, 10, true); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 10, true); assertTrue(write(10)); verifyWrite(STREAM_A, 10); @@ -213,10 +220,10 @@ public void emptyFrameAtHeadIsWritten() throws Http2Exception { @Test public void streamWindowExhaustedDoesNotWrite() throws Http2Exception { - updateStream(STREAM_A, 0, true, false); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true, false); + initState(STREAM_A, 0, true, false); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true, false); assertFalse(write(10)); verifyWrite(STREAM_B, 0); @@ -224,38 +231,30 @@ public void streamWindowExhaustedDoesNotWrite() throws Http2Exception { verifyNoMoreInteractions(writer); } + @Test + public void streamWindowLargerThanIntDoesNotInfiniteLoop() throws Http2Exception { + initState(STREAM_A, Integer.MAX_VALUE + 1L, true, true); + assertTrue(write(Integer.MAX_VALUE)); + verifyWrite(STREAM_A, Integer.MAX_VALUE); + assertFalse(write(1)); + verifyWrite(STREAM_A, 1); + } + private Http2Stream stream(int streamId) { return connection.stream(streamId); } - private void updateStream(final int streamId, final int streamableBytes, final boolean hasFrame) { - updateStream(streamId, streamableBytes, hasFrame, hasFrame); + private void initState(final int streamId, final long streamableBytes, final boolean hasFrame) { + initState(streamId, streamableBytes, hasFrame, hasFrame); } - private void updateStream(final int streamId, final int pendingBytes, final boolean hasFrame, + private void initState(final int streamId, final long pendingBytes, final boolean hasFrame, final boolean isWriteAllowed) { final Http2Stream stream = stream(streamId); - distributor.updateStreamableBytes(new StreamByteDistributor.StreamState() { - @Override - public Http2Stream stream() { - return stream; - } - - @Override - public int pendingBytes() { - return pendingBytes; - } - - @Override - public boolean hasFrame() { - return hasFrame; - } - - @Override - public int windowSize() { - return isWriteAllowed ? pendingBytes : -1; - } - }); + TestStreamByteDistributorStreamState state = new TestStreamByteDistributorStreamState(stream, pendingBytes, + hasFrame, isWriteAllowed); + stateMap.put(streamId, state); + distributor.updateStreamableBytes(state); } private void setPriority(int streamId, int parent, int weight, boolean exclusive) { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java index d9b51ec2d27..4bef8ca8194 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java @@ -95,16 +95,16 @@ private void setup(int maxStateOnlySize) throws Http2Exception { */ @Test public void writeWithNonActiveStreamShouldNotDobuleAddToPriorityQueue() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); setPriority(STREAM_D, STREAM_C, DEFAULT_PRIORITY_WEIGHT, true); // Block B, but it should still remain in the queue/tree structure. - updateStream(STREAM_B, 0, false); + initState(STREAM_B, 0, false); // Get the streams before the write, because they may be be closed. Http2Stream streamA = stream(STREAM_A); @@ -124,10 +124,10 @@ public void writeWithNonActiveStreamShouldNotDobuleAddToPriorityQueue() throws H @Test public void bytesUnassignedAfterProcessing() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); assertFalse(write(10)); verifyWrite(STREAM_A, 1); @@ -144,10 +144,10 @@ public void bytesUnassignedAfterProcessing() throws Http2Exception { @Test public void connectionErrorForWriterException() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); Exception fakeException = new RuntimeException("Fake exception"); doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3)); @@ -187,10 +187,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { setPriority(STREAM_D, STREAM_A, (short) 100, false); // Update the streams. - updateStream(STREAM_A, ALLOCATION_QUANTUM, true); - updateStream(STREAM_B, ALLOCATION_QUANTUM, true); - updateStream(STREAM_C, ALLOCATION_QUANTUM, true); - updateStream(STREAM_D, ALLOCATION_QUANTUM, true); + initState(STREAM_A, ALLOCATION_QUANTUM, true); + initState(STREAM_B, ALLOCATION_QUANTUM, true); + initState(STREAM_C, ALLOCATION_QUANTUM, true); + initState(STREAM_D, ALLOCATION_QUANTUM, true); // Only write 3 * chunkSize, so that we'll only write to the first 3 streams. int written = 3 * ALLOCATION_QUANTUM; @@ -234,10 +234,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { */ @Test public void emptyFrameAtHeadIsWritten() throws Http2Exception { - updateStream(STREAM_A, 0, true); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 0, true); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 10, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -280,7 +280,7 @@ public void blockedStreamNoDataShouldSpreadDataToChildren() throws Http2Exceptio @Test public void blockedStreamWithDataAndNotAllowedToSendShouldSpreadDataToChildren() throws Http2Exception { // A cannot stream. - updateStream(STREAM_A, 0, true, false, false); + initState(STREAM_A, 0, true, false); blockedStreamShouldSpreadDataToChildren(false); } @@ -299,23 +299,23 @@ public void blockedStreamWithDataAndNotAllowedToSendShouldSpreadDataToChildren() */ @Test public void streamWithZeroFlowControlWindowAndDataShouldWriteOnlyOnce() throws Http2Exception { - updateStream(STREAM_A, 0, true, true, false); + initState(STREAM_A, 0, true, true); blockedStreamShouldSpreadDataToChildren(true); // Make sure if we call update stream again, A should write 1 more time. - updateStream(STREAM_A, 0, true, true, false); + initState(STREAM_A, 0, true, true); assertFalse(write(1)); verifyWrite(times(2), STREAM_A, 0); - // Try to write again, but since no updateStream A should not write again + // Try to write again, but since no initState A should not write again assertFalse(write(1)); verifyWrite(times(2), STREAM_A, 0); } private void blockedStreamShouldSpreadDataToChildren(boolean streamAShouldWriteZero) throws Http2Exception { - updateStream(STREAM_B, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_B, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -375,9 +375,9 @@ private void blockedStreamShouldSpreadDataToChildren(boolean streamAShouldWriteZ @Test public void childrenShouldNotSendDataUntilParentBlocked() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -404,9 +404,9 @@ public void childrenShouldNotSendDataUntilParentBlocked() throws Http2Exception @Test public void parentShouldWaterFallDataToChildren() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 5, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 5, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -449,9 +449,9 @@ public void parentShouldWaterFallDataToChildren() throws Http2Exception { @Test public void reprioritizeShouldAdjustOutboundFlow() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Re-prioritize D as a direct child of the connection. setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false); @@ -494,7 +494,7 @@ public void unstreamableParentsShouldFeedHungryChildren() throws Http2Exception // Send enough so it can not be completely written out final int expectedUnsentAmount = 1; - updateStream(STREAM_D, writableBytes + expectedUnsentAmount, true); + initState(STREAM_D, writableBytes + expectedUnsentAmount, true); assertTrue(write(writableBytes)); verifyWrite(STREAM_D, writableBytes); @@ -521,10 +521,10 @@ public void writeShouldPreferHighestWeight() throws Http2Exception { setPriority(STREAM_C, 0, (short) 100, false); setPriority(STREAM_D, 0, (short) 100, false); - updateStream(STREAM_A, 1000, true); - updateStream(STREAM_B, 1000, true); - updateStream(STREAM_C, 1000, true); - updateStream(STREAM_D, 1000, true); + initState(STREAM_A, 1000, true); + initState(STREAM_B, 1000, true); + initState(STREAM_C, 1000, true); + initState(STREAM_D, 1000, true); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -556,10 +556,10 @@ public void writeShouldFavorPriority() throws Http2Exception { setPriority(STREAM_C, 0, (short) 100, false); setPriority(STREAM_D, 0, (short) 100, false); - updateStream(STREAM_A, 1000, true); - updateStream(STREAM_B, 1000, true); - updateStream(STREAM_C, 1000, false); - updateStream(STREAM_D, 1000, false); + initState(STREAM_A, 1000, true); + initState(STREAM_B, 1000, true); + initState(STREAM_C, 1000, false); + initState(STREAM_D, 1000, false); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -615,10 +615,10 @@ public void samePriorityShouldDistributeBasedOnData() throws Http2Exception { setPriority(STREAM_C, 0, DEFAULT_PRIORITY_WEIGHT, false); setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false); - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 700, true); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -655,10 +655,10 @@ public void samePriorityShouldDistributeBasedOnData() throws Http2Exception { */ @Test public void zeroDistributeShouldWriteAllZeroFrames() throws Http2Exception { - updateStream(STREAM_A, 400, false); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true); + initState(STREAM_A, 400, false); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -698,10 +698,10 @@ public void zeroDistributeShouldWriteAllZeroFrames() throws Http2Exception { */ @Test public void nonZeroDistributeShouldWriteAllZeroFramesIfAllEligibleDataIsWritten() throws Http2Exception { - updateStream(STREAM_A, 400, false); - updateStream(STREAM_B, 100, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true); + initState(STREAM_A, 400, false); + initState(STREAM_B, 100, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -740,10 +740,10 @@ public void nonZeroDistributeShouldWriteAllZeroFramesIfAllEligibleDataIsWritten( */ @Test public void bytesDistributedWithRestructureShouldBeCorrect() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -795,11 +795,11 @@ public void bytesDistributedWithAdditionShouldBeCorrect() throws Http2Exception setPriority(streamE.id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); // Send a bunch of data on each stream. - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); - updateStream(STREAM_E, 900, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); + initState(STREAM_E, 900, true); assertTrue(write(900)); assertEquals(400, captureWrites(STREAM_A)); @@ -843,10 +843,10 @@ public void bytesDistributedWithAdditionShouldBeCorrect() throws Http2Exception */ @Test public void bytesDistributedShouldBeCorrectWithInternalStreamClose() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); stream(STREAM_A).close(); @@ -883,10 +883,10 @@ public void bytesDistributedShouldBeCorrectWithInternalStreamClose() throws Http */ @Test public void bytesDistributedShouldBeCorrectWithLeafStreamClose() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); stream(STREAM_C).close(); @@ -906,13 +906,22 @@ public void bytesDistributedShouldBeCorrectWithLeafStreamClose() throws Http2Exc @Test public void activeStreamDependentOnNewNonActiveStreamGetsQuantum() throws Http2Exception { setup(0); - updateStream(STREAM_D, 700, true); + initState(STREAM_D, 700, true); setPriority(STREAM_D, STREAM_E, DEFAULT_PRIORITY_WEIGHT, true); assertFalse(write(700)); assertEquals(700, captureWrites(STREAM_D)); } + @Test + public void streamWindowLargerThanIntDoesNotInfiniteLoop() throws Http2Exception { + initState(STREAM_A, Integer.MAX_VALUE + 1L, true, true); + assertTrue(write(Integer.MAX_VALUE)); + verifyWrite(STREAM_A, Integer.MAX_VALUE); + assertFalse(write(1)); + verifyWrite(STREAM_A, 1); + } + private boolean write(int numBytes) throws Http2Exception { return distributor.distribute(numBytes, writer); }
val
val
"2017-12-19T02:41:09"
"2017-12-15T08:53:15Z"
durigon
val
netty/netty/4283_7523
netty/netty
netty/netty/4283
netty/netty/7523
[ "timestamp(timedelta=0.0, similarity=0.8439626116831509)" ]
94ab0dc4425b05e8691c0954f70c1859d0b7294c
144716f668efaa5bf4bb4175ec5513bd4f0f60b7
[ "@nmittler - So you are thinking that each stream's `pendingBytes` should be of data type `long` (and then what ever else needs to change to accommodate this)?\n", "@Scottmitch yeah that's basically it (for now). The `writableBytes` would still be an int, but streams may have more than `MAX_INT` to send. \n" ]
[]
"2017-12-19T03:54:42Z"
[ "feature" ]
Allow writing long-length objects in HTTP/2 flow control
This is just to capture the data byte we use for `streamableBytes`. It should be changed to `long` to support very large objects (e.g. FileRegion). @Scottmitch FYI
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java index 034140c81f8..6e02e7cecf5 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2RemoteFlowController.java @@ -16,7 +16,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.StreamByteDistributor.Writer; -import io.netty.util.BooleanSupplier; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -274,7 +273,7 @@ private final class FlowState implements StreamByteDistributor.StreamState { private final Http2Stream stream; private final Deque<FlowControlled> pendingWriteQueue; private int window; - private int pendingBytes; + private long pendingBytes; private boolean markedWritable; /** @@ -285,12 +284,6 @@ private final class FlowState implements StreamByteDistributor.StreamState { * Set to true if cancel() was called. */ private boolean cancelled; - private BooleanSupplier isWritableSupplier = new BooleanSupplier() { - @Override - public boolean get() throws Exception { - return windowSize() > pendingBytes(); - } - }; FlowState(Http2Stream stream) { this.stream = stream; @@ -302,11 +295,7 @@ public boolean get() throws Exception { * @return {@code true} if the stream associated with this object is writable. */ boolean isWritable() { - try { - return isWritableSupplier.get(); - } catch (Throwable cause) { - throw new Error("isWritableSupplier should never throw!", cause); - } + return windowSize() > pendingBytes() && !cancelled; } /** @@ -432,7 +421,7 @@ private int writableWindow() { } @Override - public int pendingBytes() { + public long pendingBytes() { return pendingBytes; } @@ -502,7 +491,6 @@ private void cancel(Throwable cause) { streamByteDistributor.updateStreamableBytes(this); - isWritableSupplier = BooleanSupplier.FALSE_SUPPLIER; monitor.stateCancelled(this); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java index 12bf363abc5..0854b55ccb4 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2CodecUtil.java @@ -223,7 +223,7 @@ public static void writeFrameHeader(ByteBuf out, int payloadLength, byte type, * Calculate the amount of bytes that can be sent by {@code state}. The lower bound is {@code 0}. */ public static int streamableBytes(StreamByteDistributor.StreamState state) { - return max(0, min(state.pendingBytes(), state.windowSize())); + return max(0, (int) min(state.pendingBytes(), state.windowSize())); } /** diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java index eaf47903ce4..a3127376354 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/StreamByteDistributor.java @@ -40,7 +40,7 @@ interface StreamState { * @return The amount of bytes this stream has pending to send. * @see Http2CodecUtil#streamableBytes(StreamState) */ - int pendingBytes(); + long pendingBytes(); /** * Indicates whether or not there are frames pending for this stream. diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java index c3e5e2faaa7..421d3488b20 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/UniformStreamByteDistributor.java @@ -129,13 +129,6 @@ private State state(Http2Stream stream) { return checkNotNull(stream, "stream").getProperty(stateKey); } - /** - * For testing only! - */ - int streamableBytes0(Http2Stream stream) { - return state(stream).streamableBytes; - } - /** * The remote flow control state for a single stream. */ diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java index 9a852a22d8f..b7c2cddf52c 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributor.java @@ -352,13 +352,6 @@ private State state(int streamId) { return stream != null ? state(stream) : stateOnlyMap.get(streamId); } - /** - * For testing only! - */ - int streamableBytes0(Http2Stream stream) { - return state(stream).streamableBytes; - } - /** * For testing only! */
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java index 12b177f975a..bb1e4695abf 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/AbstractWeightedFairQueueByteDistributorDependencyTest.java @@ -14,6 +14,9 @@ */ package io.netty.handler.codec.http2; +import io.netty.handler.codec.http2.Http2TestUtil.TestStreamByteDistributorStreamState; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -21,6 +24,8 @@ abstract class AbstractWeightedFairQueueByteDistributorDependencyTest { Http2Connection connection; WeightedFairQueueByteDistributor distributor; + private IntObjectMap<TestStreamByteDistributorStreamState> stateMap = + new IntObjectHashMap<TestStreamByteDistributorStreamState>(); @Mock StreamByteDistributor.Writer writer; @@ -35,45 +40,30 @@ Answer<Void> writeAnswer(final boolean closeIfNoFrame) { public Void answer(InvocationOnMock in) throws Throwable { Http2Stream stream = in.getArgument(0); int numBytes = in.getArgument(1); - int streamableBytes = distributor.streamableBytes0(stream) - numBytes; - boolean hasFrame = streamableBytes > 0; - updateStream(stream.id(), streamableBytes, hasFrame, hasFrame, closeIfNoFrame); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + state.isWriteAllowed = state.hasFrame; + if (closeIfNoFrame && !state.hasFrame) { + stream.close(); + } + distributor.updateStreamableBytes(state); return null; } }; } - void updateStream(final int streamId, final int streamableBytes, final boolean hasFrame) { - updateStream(streamId, streamableBytes, hasFrame, hasFrame, false); + void initState(final int streamId, final long streamableBytes, final boolean hasFrame) { + initState(streamId, streamableBytes, hasFrame, hasFrame); } - void updateStream(final int streamId, final int pendingBytes, final boolean hasFrame, - final boolean isWriteAllowed, boolean closeIfNoFrame) { + void initState(final int streamId, final long pendingBytes, final boolean hasFrame, + final boolean isWriteAllowed) { final Http2Stream stream = stream(streamId); - if (closeIfNoFrame && !hasFrame) { - stream(streamId).close(); - } - distributor.updateStreamableBytes(new StreamByteDistributor.StreamState() { - @Override - public Http2Stream stream() { - return stream; - } - - @Override - public int pendingBytes() { - return pendingBytes; - } - - @Override - public boolean hasFrame() { - return hasFrame; - } - - @Override - public int windowSize() { - return isWriteAllowed ? pendingBytes : -1; - } - }); + TestStreamByteDistributorStreamState state = new TestStreamByteDistributorStreamState(stream, pendingBytes, + hasFrame, isWriteAllowed); + stateMap.put(streamId, state); + distributor.updateStreamableBytes(state); } void setPriority(int streamId, int parent, int weight, boolean exclusive) throws Http2Exception { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java index 6c0b129f315..8fafd435d8d 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2TestUtil.java @@ -35,6 +35,7 @@ import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_LIST_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_TABLE_SIZE; +import static java.lang.Math.min; /** * Utilities for the integration tests. @@ -470,4 +471,39 @@ public void operationComplete(ChannelFuture future) throws Exception { } }; } + + static final class TestStreamByteDistributorStreamState implements StreamByteDistributor.StreamState { + private final Http2Stream stream; + boolean isWriteAllowed; + long pendingBytes; + boolean hasFrame; + + TestStreamByteDistributorStreamState(Http2Stream stream, long pendingBytes, boolean hasFrame, + boolean isWriteAllowed) { + this.stream = stream; + this.isWriteAllowed = isWriteAllowed; + this.pendingBytes = pendingBytes; + this.hasFrame = hasFrame; + } + + @Override + public Http2Stream stream() { + return stream; + } + + @Override + public long pendingBytes() { + return pendingBytes; + } + + @Override + public boolean hasFrame() { + return hasFrame; + } + + @Override + public int windowSize() { + return isWriteAllowed ? (int) min(pendingBytes, Integer.MAX_VALUE) : -1; + } + } } diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java index 28d8ba7bb13..c804174b8b4 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/UniformStreamByteDistributorTest.java @@ -14,6 +14,9 @@ */ package io.netty.handler.codec.http2; +import io.netty.handler.codec.http2.Http2TestUtil.TestStreamByteDistributorStreamState; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -32,13 +35,13 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.same; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; @@ -55,6 +58,7 @@ public class UniformStreamByteDistributorTest { private Http2Connection connection; private UniformStreamByteDistributor distributor; + private IntObjectMap<TestStreamByteDistributorStreamState> stateMap; @Mock private StreamByteDistributor.Writer writer; @@ -63,6 +67,7 @@ public class UniformStreamByteDistributorTest { public void setup() throws Http2Exception { MockitoAnnotations.initMocks(this); + stateMap = new IntObjectHashMap<TestStreamByteDistributorStreamState>(); connection = new DefaultHttp2Connection(false); distributor = new UniformStreamByteDistributor(connection); @@ -83,8 +88,10 @@ private Answer<Void> writeAnswer() { public Void answer(InvocationOnMock in) throws Throwable { Http2Stream stream = in.getArgument(0); int numBytes = in.getArgument(1); - int streamableBytes = distributor.streamableBytes0(stream) - numBytes; - updateStream(stream.id(), streamableBytes, streamableBytes > 0); + TestStreamByteDistributorStreamState state = stateMap.get(stream.id()); + state.pendingBytes -= numBytes; + state.hasFrame = state.pendingBytes > 0; + distributor.updateStreamableBytes(state); return null; } }; @@ -97,10 +104,10 @@ private void resetWriter() { @Test public void bytesUnassignedAfterProcessing() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); assertFalse(write(10)); verifyWrite(STREAM_A, 1); @@ -115,10 +122,10 @@ public void bytesUnassignedAfterProcessing() throws Http2Exception { @Test public void connectionErrorForWriterException() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); Exception fakeException = new RuntimeException("Fake exception"); doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3)); @@ -158,10 +165,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { setPriority(STREAM_D, STREAM_A, (short) 100, false); // Update the streams. - updateStream(STREAM_A, CHUNK_SIZE, true); - updateStream(STREAM_B, CHUNK_SIZE, true); - updateStream(STREAM_C, CHUNK_SIZE, true); - updateStream(STREAM_D, CHUNK_SIZE, true); + initState(STREAM_A, CHUNK_SIZE, true); + initState(STREAM_B, CHUNK_SIZE, true); + initState(STREAM_C, CHUNK_SIZE, true); + initState(STREAM_D, CHUNK_SIZE, true); // Only write 3 * chunkSize, so that we'll only write to the first 3 streams. int written = 3 * CHUNK_SIZE; @@ -182,7 +189,7 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { @Test public void streamWithMoreDataShouldBeEnqueuedAfterWrite() throws Http2Exception { // Give the stream a bunch of data. - updateStream(STREAM_A, 2 * CHUNK_SIZE, true); + initState(STREAM_A, 2 * CHUNK_SIZE, true); // Write only part of the data. assertTrue(write(CHUNK_SIZE)); @@ -199,10 +206,10 @@ public void streamWithMoreDataShouldBeEnqueuedAfterWrite() throws Http2Exception @Test public void emptyFrameAtHeadIsWritten() throws Http2Exception { - updateStream(STREAM_A, 10, true); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 10, true); assertTrue(write(10)); verifyWrite(STREAM_A, 10); @@ -213,10 +220,10 @@ public void emptyFrameAtHeadIsWritten() throws Http2Exception { @Test public void streamWindowExhaustedDoesNotWrite() throws Http2Exception { - updateStream(STREAM_A, 0, true, false); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true, false); + initState(STREAM_A, 0, true, false); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true, false); assertFalse(write(10)); verifyWrite(STREAM_B, 0); @@ -224,38 +231,30 @@ public void streamWindowExhaustedDoesNotWrite() throws Http2Exception { verifyNoMoreInteractions(writer); } + @Test + public void streamWindowLargerThanIntDoesNotInfiniteLoop() throws Http2Exception { + initState(STREAM_A, Integer.MAX_VALUE + 1L, true, true); + assertTrue(write(Integer.MAX_VALUE)); + verifyWrite(STREAM_A, Integer.MAX_VALUE); + assertFalse(write(1)); + verifyWrite(STREAM_A, 1); + } + private Http2Stream stream(int streamId) { return connection.stream(streamId); } - private void updateStream(final int streamId, final int streamableBytes, final boolean hasFrame) { - updateStream(streamId, streamableBytes, hasFrame, hasFrame); + private void initState(final int streamId, final long streamableBytes, final boolean hasFrame) { + initState(streamId, streamableBytes, hasFrame, hasFrame); } - private void updateStream(final int streamId, final int pendingBytes, final boolean hasFrame, + private void initState(final int streamId, final long pendingBytes, final boolean hasFrame, final boolean isWriteAllowed) { final Http2Stream stream = stream(streamId); - distributor.updateStreamableBytes(new StreamByteDistributor.StreamState() { - @Override - public Http2Stream stream() { - return stream; - } - - @Override - public int pendingBytes() { - return pendingBytes; - } - - @Override - public boolean hasFrame() { - return hasFrame; - } - - @Override - public int windowSize() { - return isWriteAllowed ? pendingBytes : -1; - } - }); + TestStreamByteDistributorStreamState state = new TestStreamByteDistributorStreamState(stream, pendingBytes, + hasFrame, isWriteAllowed); + stateMap.put(streamId, state); + distributor.updateStreamableBytes(state); } private void setPriority(int streamId, int parent, int weight, boolean exclusive) { diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java index d9b51ec2d27..4bef8ca8194 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/WeightedFairQueueByteDistributorTest.java @@ -95,16 +95,16 @@ private void setup(int maxStateOnlySize) throws Http2Exception { */ @Test public void writeWithNonActiveStreamShouldNotDobuleAddToPriorityQueue() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); setPriority(STREAM_D, STREAM_C, DEFAULT_PRIORITY_WEIGHT, true); // Block B, but it should still remain in the queue/tree structure. - updateStream(STREAM_B, 0, false); + initState(STREAM_B, 0, false); // Get the streams before the write, because they may be be closed. Http2Stream streamA = stream(STREAM_A); @@ -124,10 +124,10 @@ public void writeWithNonActiveStreamShouldNotDobuleAddToPriorityQueue() throws H @Test public void bytesUnassignedAfterProcessing() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); assertFalse(write(10)); verifyWrite(STREAM_A, 1); @@ -144,10 +144,10 @@ public void bytesUnassignedAfterProcessing() throws Http2Exception { @Test public void connectionErrorForWriterException() throws Http2Exception { - updateStream(STREAM_A, 1, true); - updateStream(STREAM_B, 2, true); - updateStream(STREAM_C, 3, true); - updateStream(STREAM_D, 4, true); + initState(STREAM_A, 1, true); + initState(STREAM_B, 2, true); + initState(STREAM_C, 3, true); + initState(STREAM_D, 4, true); Exception fakeException = new RuntimeException("Fake exception"); doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3)); @@ -187,10 +187,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { setPriority(STREAM_D, STREAM_A, (short) 100, false); // Update the streams. - updateStream(STREAM_A, ALLOCATION_QUANTUM, true); - updateStream(STREAM_B, ALLOCATION_QUANTUM, true); - updateStream(STREAM_C, ALLOCATION_QUANTUM, true); - updateStream(STREAM_D, ALLOCATION_QUANTUM, true); + initState(STREAM_A, ALLOCATION_QUANTUM, true); + initState(STREAM_B, ALLOCATION_QUANTUM, true); + initState(STREAM_C, ALLOCATION_QUANTUM, true); + initState(STREAM_D, ALLOCATION_QUANTUM, true); // Only write 3 * chunkSize, so that we'll only write to the first 3 streams. int written = 3 * ALLOCATION_QUANTUM; @@ -234,10 +234,10 @@ public void minChunkShouldBeAllocatedPerStream() throws Http2Exception { */ @Test public void emptyFrameAtHeadIsWritten() throws Http2Exception { - updateStream(STREAM_A, 0, true); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 0, true); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 10, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -280,7 +280,7 @@ public void blockedStreamNoDataShouldSpreadDataToChildren() throws Http2Exceptio @Test public void blockedStreamWithDataAndNotAllowedToSendShouldSpreadDataToChildren() throws Http2Exception { // A cannot stream. - updateStream(STREAM_A, 0, true, false, false); + initState(STREAM_A, 0, true, false); blockedStreamShouldSpreadDataToChildren(false); } @@ -299,23 +299,23 @@ public void blockedStreamWithDataAndNotAllowedToSendShouldSpreadDataToChildren() */ @Test public void streamWithZeroFlowControlWindowAndDataShouldWriteOnlyOnce() throws Http2Exception { - updateStream(STREAM_A, 0, true, true, false); + initState(STREAM_A, 0, true, true); blockedStreamShouldSpreadDataToChildren(true); // Make sure if we call update stream again, A should write 1 more time. - updateStream(STREAM_A, 0, true, true, false); + initState(STREAM_A, 0, true, true); assertFalse(write(1)); verifyWrite(times(2), STREAM_A, 0); - // Try to write again, but since no updateStream A should not write again + // Try to write again, but since no initState A should not write again assertFalse(write(1)); verifyWrite(times(2), STREAM_A, 0); } private void blockedStreamShouldSpreadDataToChildren(boolean streamAShouldWriteZero) throws Http2Exception { - updateStream(STREAM_B, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_B, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -375,9 +375,9 @@ private void blockedStreamShouldSpreadDataToChildren(boolean streamAShouldWriteZ @Test public void childrenShouldNotSendDataUntilParentBlocked() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -404,9 +404,9 @@ public void childrenShouldNotSendDataUntilParentBlocked() throws Http2Exception @Test public void parentShouldWaterFallDataToChildren() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 5, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 5, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Write up to 10 bytes. assertTrue(write(10)); @@ -449,9 +449,9 @@ public void parentShouldWaterFallDataToChildren() throws Http2Exception { @Test public void reprioritizeShouldAdjustOutboundFlow() throws Http2Exception { // B cannot stream. - updateStream(STREAM_A, 10, true); - updateStream(STREAM_C, 10, true); - updateStream(STREAM_D, 10, true); + initState(STREAM_A, 10, true); + initState(STREAM_C, 10, true); + initState(STREAM_D, 10, true); // Re-prioritize D as a direct child of the connection. setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false); @@ -494,7 +494,7 @@ public void unstreamableParentsShouldFeedHungryChildren() throws Http2Exception // Send enough so it can not be completely written out final int expectedUnsentAmount = 1; - updateStream(STREAM_D, writableBytes + expectedUnsentAmount, true); + initState(STREAM_D, writableBytes + expectedUnsentAmount, true); assertTrue(write(writableBytes)); verifyWrite(STREAM_D, writableBytes); @@ -521,10 +521,10 @@ public void writeShouldPreferHighestWeight() throws Http2Exception { setPriority(STREAM_C, 0, (short) 100, false); setPriority(STREAM_D, 0, (short) 100, false); - updateStream(STREAM_A, 1000, true); - updateStream(STREAM_B, 1000, true); - updateStream(STREAM_C, 1000, true); - updateStream(STREAM_D, 1000, true); + initState(STREAM_A, 1000, true); + initState(STREAM_B, 1000, true); + initState(STREAM_C, 1000, true); + initState(STREAM_D, 1000, true); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -556,10 +556,10 @@ public void writeShouldFavorPriority() throws Http2Exception { setPriority(STREAM_C, 0, (short) 100, false); setPriority(STREAM_D, 0, (short) 100, false); - updateStream(STREAM_A, 1000, true); - updateStream(STREAM_B, 1000, true); - updateStream(STREAM_C, 1000, false); - updateStream(STREAM_D, 1000, false); + initState(STREAM_A, 1000, true); + initState(STREAM_B, 1000, true); + initState(STREAM_C, 1000, false); + initState(STREAM_D, 1000, false); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -615,10 +615,10 @@ public void samePriorityShouldDistributeBasedOnData() throws Http2Exception { setPriority(STREAM_C, 0, DEFAULT_PRIORITY_WEIGHT, false); setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false); - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 700, true); // Set allocation quantum to 1 so it is easier to see the ratio of total bytes written between each stream. distributor.allocationQuantum(1); @@ -655,10 +655,10 @@ public void samePriorityShouldDistributeBasedOnData() throws Http2Exception { */ @Test public void zeroDistributeShouldWriteAllZeroFrames() throws Http2Exception { - updateStream(STREAM_A, 400, false); - updateStream(STREAM_B, 0, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true); + initState(STREAM_A, 400, false); + initState(STREAM_B, 0, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -698,10 +698,10 @@ public void zeroDistributeShouldWriteAllZeroFrames() throws Http2Exception { */ @Test public void nonZeroDistributeShouldWriteAllZeroFramesIfAllEligibleDataIsWritten() throws Http2Exception { - updateStream(STREAM_A, 400, false); - updateStream(STREAM_B, 100, true); - updateStream(STREAM_C, 0, true); - updateStream(STREAM_D, 0, true); + initState(STREAM_A, 400, false); + initState(STREAM_B, 100, true); + initState(STREAM_C, 0, true); + initState(STREAM_D, 0, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -740,10 +740,10 @@ public void nonZeroDistributeShouldWriteAllZeroFramesIfAllEligibleDataIsWritten( */ @Test public void bytesDistributedWithRestructureShouldBeCorrect() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); setPriority(STREAM_B, STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); @@ -795,11 +795,11 @@ public void bytesDistributedWithAdditionShouldBeCorrect() throws Http2Exception setPriority(streamE.id(), STREAM_A, DEFAULT_PRIORITY_WEIGHT, true); // Send a bunch of data on each stream. - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); - updateStream(STREAM_E, 900, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); + initState(STREAM_E, 900, true); assertTrue(write(900)); assertEquals(400, captureWrites(STREAM_A)); @@ -843,10 +843,10 @@ public void bytesDistributedWithAdditionShouldBeCorrect() throws Http2Exception */ @Test public void bytesDistributedShouldBeCorrectWithInternalStreamClose() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); stream(STREAM_A).close(); @@ -883,10 +883,10 @@ public void bytesDistributedShouldBeCorrectWithInternalStreamClose() throws Http */ @Test public void bytesDistributedShouldBeCorrectWithLeafStreamClose() throws Http2Exception { - updateStream(STREAM_A, 400, true); - updateStream(STREAM_B, 500, true); - updateStream(STREAM_C, 600, true); - updateStream(STREAM_D, 700, true); + initState(STREAM_A, 400, true); + initState(STREAM_B, 500, true); + initState(STREAM_C, 600, true); + initState(STREAM_D, 700, true); stream(STREAM_C).close(); @@ -906,13 +906,22 @@ public void bytesDistributedShouldBeCorrectWithLeafStreamClose() throws Http2Exc @Test public void activeStreamDependentOnNewNonActiveStreamGetsQuantum() throws Http2Exception { setup(0); - updateStream(STREAM_D, 700, true); + initState(STREAM_D, 700, true); setPriority(STREAM_D, STREAM_E, DEFAULT_PRIORITY_WEIGHT, true); assertFalse(write(700)); assertEquals(700, captureWrites(STREAM_D)); } + @Test + public void streamWindowLargerThanIntDoesNotInfiniteLoop() throws Http2Exception { + initState(STREAM_A, Integer.MAX_VALUE + 1L, true, true); + assertTrue(write(Integer.MAX_VALUE)); + verifyWrite(STREAM_A, Integer.MAX_VALUE); + assertFalse(write(1)); + verifyWrite(STREAM_A, 1); + } + private boolean write(int numBytes) throws Http2Exception { return distributor.distribute(numBytes, writer); }
train
val
"2017-12-19T02:41:09"
"2015-09-25T18:25:20Z"
nmittler
val
netty/netty/7514_7531
netty/netty
netty/netty/7514
netty/netty/7531
[ "keyword_pr_to_issue", "timestamp(timedelta=0.0, similarity=0.8670675281921579)" ]
c9668ce40f80f73763165a8bfe70969de830204c
6b033c51a50e96714bf6939bd8a7706ee173d8e6
[ "@mosesn are you planing to work on a PR / unit test ?", "Not right now, maybe in the next couple months? It's not causing us a problem, it just made debugging an issue we ran into a bit harder.", "@mosesn got it", "I may have a go at it. Sounds simple enough 😝 ", "@madgnome yay :)", "Thanks @madgnome!" ]
[ "just change this to `catch (Http2Exception.HeaderListSizeException expected)` and remove the `assertTrue(...)` below ?", "fyi, in the future, this should be final", "https://github.com/netty/netty/pull/7596" ]
"2017-12-21T10:59:59Z"
[]
hpackdecoder doesn't account for header overhead
Http/2 says for max header list size: > SETTINGS_MAX_HEADER_LIST_SIZE (0x6): This advisory setting informs a > peer of the maximum size of header list that the sender is > prepared to accept, in octets. The value is based on the > uncompressed size of header fields, including the length of the > name and value in octets plus an overhead of 32 octets for each > header field. > > For any given request, a lower limit than what is advertised MAY > be enforced. The initial value of this setting is unlimited. In HpackEncoder, we account for the 32 bytes, but when decoding, we don't. The way I found this was by setting up a finagle proxy talking to a finagle server. When I curled the server directly, I was way beneath the limit, but when I curled the proxy, I got 431s, since it correctly accounted for the 32 bytes overhead on the client-side in HpackEncoder.
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java index 07b1e30b535..ca7610816d2 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java @@ -429,7 +429,7 @@ private long insertHeader(int streamId, Http2Headers headers, CharSequence name, private long addHeader(int streamId, Http2Headers headers, CharSequence name, CharSequence value, long headersLength) throws Http2Exception { - headersLength += name.length() + value.length(); + headersLength += HpackHeaderField.sizeOf(name, value); if (headersLength > maxHeaderListSizeGoAway) { headerListSizeExceeded(maxHeaderListSizeGoAway); }
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java index 04552b9263e..18220338882 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java @@ -35,14 +35,19 @@ import io.netty.buffer.Unpooled; import io.netty.util.internal.StringUtil; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import static io.netty.handler.codec.http2.HpackDecoder.decodeULE128; import static io.netty.handler.codec.http2.Http2HeadersEncoder.NEVER_SENSITIVE; import static io.netty.util.AsciiString.EMPTY_STRING; import static io.netty.util.AsciiString.of; import static java.lang.Integer.MAX_VALUE; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; @@ -52,6 +57,9 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; public class HpackDecoderTest { + @Rule + public ExpectedException expectedException = ExpectedException.none(); + private HpackDecoder hpackDecoder; private Http2Headers mockHeaders; @@ -425,9 +433,9 @@ public void testLiteralNeverIndexedWithLargeValue() throws Http2Exception { @Test public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSizeUpdatesDynamicTable() throws Http2Exception { - ByteBuf in = Unpooled.buffer(200); + ByteBuf in = Unpooled.buffer(300); try { - hpackDecoder.setMaxHeaderListSize(100, 200); + hpackDecoder.setMaxHeaderListSize(200, 300); HpackEncoder hpackEncoder = new HpackEncoder(true); // encode headers that are slightly larger than maxHeaderListSize @@ -477,4 +485,31 @@ public void testDecodeCountsNamesOnlyOnce() throws Http2Exception { in.release(); } } + + @Test + public void testAccountForHeaderOverhead() throws Exception { + ByteBuf in = Unpooled.buffer(100); + try { + String headerName = "12345"; + String headerValue = "56789"; + long headerSize = headerName.length() + headerValue.length(); + hpackDecoder.setMaxHeaderListSize(headerSize, 100); + HpackEncoder hpackEncoder = new HpackEncoder(true); + + Http2Headers toEncode = new DefaultHttp2Headers(); + toEncode.add(headerName, headerValue); + hpackEncoder.encodeHeaders(1, in, toEncode, NEVER_SENSITIVE); + + Http2Headers decoded = new DefaultHttp2Headers(); + + // SETTINGS_MAX_HEADER_LIST_SIZE is big enough for the header to fit... + assertThat(hpackDecoder.getMaxHeaderListSize(), is(greaterThanOrEqualTo(headerSize))); + + // ... but decode should fail because we add some overhead for each header entry + expectedException.expect(Http2Exception.HeaderListSizeException.class); + hpackDecoder.decode(1, in, decoded); + } finally { + in.release(); + } + } }
val
val
"2017-12-21T07:41:38"
"2017-12-16T22:29:04Z"
mosesn
val
netty/netty/6320_7544
netty/netty
netty/netty/6320
netty/netty/7544
[ "timestamp(timedelta=0.0, similarity=0.8480668595327252)" ]
b6c42f6547e6621dd924707167db83b15652d7f6
e24e06bfcb8114270d46572cf96af49be76237b1
[ "OpenSSL 1.1.0e cannot be used in netty-tcnative, because SSL_set_state no longer exists in OpenSSL since 1.1.0 (https://github.com/netty/netty-tcnative/issues/263).\r\nGiven that OpenSSL 1.1.1 (hopefully) supports TLS 1.3, it seems worth to remove usage of SSL_set_state.", "I don't know if this helps, but this is how apache tcnative does the renegotiation (in an older version): https://github.com/apache/tomcat-native/blob/043f95087f712595598901b7c5f915ca5fbf86d5/native/src/sslnetwork.c#L650\r\nIn the trunk they removed the `SSL_set_state` call completely: https://github.com/apache/tomcat-native/blob/trunk/native/src/sslnetwork.c#L632", "@Scottmitch I wonder if we should just remove the support for `renegotiation` as its risky business anyway. This would also allow us to just drop `set_state` usage and so support openssl 1.1.x.\r\n\r\nWDYT ?\r\n\r\n@carl-mastrangelo @ejona86 @nmittler WDYT as well?", "+1", "I honestly don't know enough to determine whether renegotiation is necessary or alternative approaches." ]
[]
"2017-12-23T13:26:03Z"
[]
OpenSslEngine should not call SSL_set_state
OpenSslEngine currently calls `SSL_set_state(SSL_ST_ACCEPT)` during the renegotiation process. The OpenSSL team has advised against this [1]. We should investigate and avoid calling `SSL_ST_ACCEPT` if possible. [1] https://github.com/openssl/openssl/issues/2551#issuecomment-277644153
[ "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java index 360d9fd9ab2..d235653cfd4 100644 --- a/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java +++ b/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java @@ -163,7 +163,6 @@ private enum HandshakeState { } private HandshakeState handshakeState = HandshakeState.NOT_STARTED; - private boolean renegotiationPending; private boolean receivedShutdown; private volatile int destroyed; private volatile String applicationProtocol; @@ -654,17 +653,6 @@ public final SSLEngineResult wrap( status = handshake(); - if (renegotiationPending && status == FINISHED) { - // If renegotiationPending is true that means when we attempted to start renegotiation - // the BIO buffer didn't have enough space to hold the HelloRequest which prompts the - // client to initiate a renegotiation. At this point the HelloRequest has been written - // so we can actually start the handshake process. - renegotiationPending = false; - SSL.setState(ssl, SSL.SSL_ST_ACCEPT); - handshakeState = HandshakeState.STARTED_EXPLICITLY; - status = handshake(); - } - // Handshake may have generated more data, for example if the internal SSL buffer is small // we may have freed up space by flushing above. bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO); @@ -1510,43 +1498,7 @@ public final synchronized void beginHandshake() throws SSLException { // Nothing to do as the handshake is not done yet. break; case FINISHED: - if (clientMode) { - // Only supported for server mode at the moment. - throw RENEGOTIATION_UNSUPPORTED; - } - // For renegotiate on the server side we need to issue the following command sequence with openssl: - // - // SSL_renegotiate(ssl) - // SSL_do_handshake(ssl) - // ssl->state = SSL_ST_ACCEPT - // SSL_do_handshake(ssl) - // - // Because of this we fall-through to call handshake() after setting the state, as this will also take - // care of updating the internal OpenSslSession object. - // - // See also: - // https://github.com/apache/httpd/blob/2.4.16/modules/ssl/ssl_engine_kernel.c#L812 - // http://h71000.www7.hp.com/doc/83final/ba554_90007/ch04s03.html - int status; - if ((status = SSL.renegotiate(ssl)) != 1 || (status = SSL.doHandshake(ssl)) != 1) { - int err = SSL.getError(ssl, status); - if (err == SSL.SSL_ERROR_WANT_READ || err == SSL.SSL_ERROR_WANT_WRITE) { - // If the internal SSL buffer is small it is possible that doHandshake may "fail" because - // there is not enough room to write, so we should wait until the renegotiation has been. - renegotiationPending = true; - handshakeState = HandshakeState.STARTED_EXPLICITLY; - lastAccessed = System.currentTimeMillis(); - return; - } else { - throw shutdownWithError("renegotiation failed"); - } - } - - SSL.setState(ssl, SSL.SSL_ST_ACCEPT); - - lastAccessed = System.currentTimeMillis(); - - // fall-through + throw RENEGOTIATION_UNSUPPORTED; case NOT_STARTED: handshakeState = HandshakeState.STARTED_EXPLICITLY; handshake();
diff --git a/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateSmallBIOTest.java b/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateSmallBIOTest.java deleted file mode 100644 index 3959e646998..00000000000 --- a/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateSmallBIOTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2017 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package io.netty.handler.ssl; - -public class OpenSslRenegotiateSmallBIOTest extends OpenSslRenegotiateTest { - @Override - protected void initSslServerContext(SslContext context) { - ((ReferenceCountedOpenSslContext) context).setBioNonApplicationBufferSize(1); - } -} diff --git a/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateTest.java b/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateTest.java deleted file mode 100644 index 8f3dfeea7f2..00000000000 --- a/handler/src/test/java/io/netty/handler/ssl/OpenSslRenegotiateTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2015 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package io.netty.handler.ssl; - -import org.junit.BeforeClass; - -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -public class OpenSslRenegotiateTest extends RenegotiateTest { - - @BeforeClass - public static void checkOpenSsl() { - assumeTrue(OpenSsl.isAvailable()); - // BoringSSL does not support renegotiation intentionally. - assumeFalse("BoringSSL".equals(OpenSsl.versionString())); - } - - @Override - protected SslProvider serverSslProvider() { - return SslProvider.OPENSSL; - } -}
train
val
"2017-12-22T19:32:56"
"2017-02-06T19:46:20Z"
Scottmitch
val
netty/netty/7561_7562
netty/netty
netty/netty/7561
netty/netty/7562
[ "timestamp(timedelta=19.0, similarity=0.9280960646913106)" ]
4c1e0f596ad25bf891570ea67c5322a35938bfa5
3b81d8791438b7f8424effbf23cf139b95491d85
[ "Fixed by https://github.com/netty/netty/pull/7562" ]
[ "Please use the same strategy as https://github.com/netty/netty/commit/942b993f2b9781ff2126ff92a6be5b975dfc72ed#diff-17c17dd59c9912dd08e4dc95fa04bcab. In summary adding a `copy()` method on `DefaultStompHeaders` which leverages `DefaultHeaders#copy()`.", "I looked to this strategy but `DefaultStompHeaders extends DefaultHeader implements StompHeaders` we can't add `StompHeaders#copy()` method it will be clashes. Maybe we can add method with name like a `StompHeaders#deepCopy()` or another way ?", "We can't modify `StompHeaders` because it is an interface and that would be an API breaking change. However we can modify `DefaultStompHeaders` and do the following:\r\n\r\n```java\r\n @Override\r\n public DefaultStompHeaders copy() {\r\n DefaultStompHeaders copy = new DefaultStompHeaders();\r\n copy.addImpl(this);\r\n return copy;\r\n }\r\n```\r\n\r\nWe could also modify `DefaultHeaders` so we can consolidate the `copy.addImpl`, and any other work which maybe necessary in the future, but this maybe unnecessary.", "So we can, but in `DefaultStompHeadersSubframe` used interface `StompHeaders`, how we can access to method that not present in interface without casting or other trick? Maybe I misunderstood you.", "@Scottmitch I understand that you are busy, but I would like to quickly close this defect.", "> how we can access to method that not present in interface without casting or other trick? \r\n\r\nUnfortunately before jdk8 (which provides the `default` key word) extending interfaces is not possible without breaking API changes. So we have a few options:\r\n\r\n1. No API breaking changed but just add a `DefaultStompHeaders copy()` method (as suggested above)\r\n- change the member variable in `DefaultStompHeadersSubframe` so it is declared as type `DefaultStompHeaders`.\r\n- make the new constructor in `DefaultStompHeadersSubframe` which currently takes a `StompHeaders` instead take a `DefaultStompHeaders` and make it package private\r\n2. \"break\" the StompHeaders API and add a `StompHeaders copy()` method (and also override this method in `DefaultStompHeaders` as suggested above).\r\n\r\n@normanmaurer - my guess is you would prefer the \"non-breaking\" API change? However maybe its ok because its STOMP...", "I think you also need to call `release()` on the frames ?", "You mean that `release()` not affect a copied frame or that is work correct by spec ?", "Basically add:\r\n\r\n```java\r\nsourceFrame.release();\r\ncopyFrame.release();\r\n```\r\n\r\nThis is needed as `DefaultStompFrame` implementations `ByteBufHolder` to ensure there are no memory leaks.", "@amizurov can you explain why the changes to this class are needed at all ? I think you can revert the changes", "So, when we create `new DefaultStompFrame` in `DefaultStompFrame#replace(...)` method we pass `headers.copy()` to the constructor.\r\n", "But not to this class", "It's super class for `DefaultStompFrame`, else it's will be look like this: \r\n ```java\r\nDefaultStompFrame(StompCommand command, ByteBuf content, DefaultStompHeaders \r\nheaders) {\r\n super(command);\r\n\r\n if (headers != null) {\r\n this.headers.set(headers);\r\n }\r\n\r\n if (content == null) {\r\n throw new NullPointerException(\"content\");\r\n }\r\n this.content = content;\r\n }\r\n```\r\n\r\nor many other variation, I think that is not very clear. Look at `DefaultFullHttpRequest` we try use same approach.", "@normanmaurer - This was option (1) from https://github.com/netty/netty/pull/7562#discussion_r163063162 and is necessary so `DefaultStompFrame` can call `copy()` on the `DefaultStompHeaders` class (which isn't present in `StompHeaders`).", "never mind missed it is the super-class. " ]
"2018-01-03T16:19:18Z"
[ "defect" ]
StompFrame.copy() does not copy headers
### Expected behavior Call stompFrame.copy() do copies of content and headers. ### Actual behavior After call stompFrame.copy() only content was copy. ### Minimal yet complete reproducer code (or URL to code) `StompFrame stompFrame = new DefaultStompFrame(StompCommand.CONNECT);` `stompFrame.headers().set(StompHeaders.HOST, "localhost");` `StompFrame copyFrame = stompFrame.copy();` `Assert.assertTrue(copyFrame.headers().isEmpty());` ### Netty version 4.1.20.Final ### JVM version (e.g. `java -version`) java version "1.8.0_151" Java(TM) SE Runtime Environment (build 1.8.0_151-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode) ### OS version (e.g. `uname -a`) Darwin Kernel Version 16.7.0: Mon Nov 13 21:56:25 PST 2017; root:xnu-3789.72.11~1/RELEASE_X86_64 x86_64
[ "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java", "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java", "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java" ]
[ "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java", "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java", "codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java" ]
[ "codec-stomp/src/test/java/io/netty/handler/codec/stomp/DefaultStompFrameTest.java" ]
diff --git a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java index d113ed6f2b7..8df4c650439 100644 --- a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java +++ b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompFrame.java @@ -31,10 +31,16 @@ public DefaultStompFrame(StompCommand command) { } public DefaultStompFrame(StompCommand command, ByteBuf content) { - super(command); + this(command, content, null); + } + + DefaultStompFrame(StompCommand command, ByteBuf content, DefaultStompHeaders headers) { + super(command, headers); + if (content == null) { throw new NullPointerException("content"); } + this.content = content; } @@ -60,7 +66,7 @@ public StompFrame retainedDuplicate() { @Override public StompFrame replace(ByteBuf content) { - return new DefaultStompFrame(command, content); + return new DefaultStompFrame(command, content, headers.copy()); } @Override diff --git a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java index 80fccf0f668..e9ad5b8d5b3 100644 --- a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java +++ b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeaders.java @@ -16,14 +16,14 @@ package io.netty.handler.codec.stomp; -import io.netty.handler.codec.CharSequenceValueConverter; -import io.netty.handler.codec.DefaultHeaders; -import io.netty.handler.codec.HeadersUtils; - import java.util.Iterator; import java.util.List; import java.util.Map.Entry; +import io.netty.handler.codec.CharSequenceValueConverter; +import io.netty.handler.codec.DefaultHeaders; +import io.netty.handler.codec.HeadersUtils; + import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER; import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER; @@ -58,4 +58,11 @@ public boolean contains(CharSequence name, CharSequence value, boolean ignoreCas return contains(name, value, ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER); } + + @Override + public DefaultStompHeaders copy() { + DefaultStompHeaders copyHeaders = new DefaultStompHeaders(); + copyHeaders.addImpl(this); + return copyHeaders; + } } diff --git a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java index ca7db33d13c..728a8894bea 100644 --- a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java +++ b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/DefaultStompHeadersSubframe.java @@ -24,13 +24,19 @@ public class DefaultStompHeadersSubframe implements StompHeadersSubframe { protected final StompCommand command; protected DecoderResult decoderResult = DecoderResult.SUCCESS; - protected final StompHeaders headers = new DefaultStompHeaders(); + protected final DefaultStompHeaders headers; public DefaultStompHeadersSubframe(StompCommand command) { + this(command, null); + } + + DefaultStompHeadersSubframe(StompCommand command, DefaultStompHeaders headers) { if (command == null) { throw new NullPointerException("command"); } + this.command = command; + this.headers = headers == null ? new DefaultStompHeaders() : headers; } @Override
diff --git a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/DefaultStompFrameTest.java b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/DefaultStompFrameTest.java new file mode 100644 index 00000000000..c995ca7f1b8 --- /dev/null +++ b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/DefaultStompFrameTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.stomp; + +import io.netty.util.AsciiString; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class DefaultStompFrameTest { + + @Test + public void testStompFrameCopy() { + StompFrame sourceFrame = new DefaultStompFrame(StompCommand.CONNECT); + + assertTrue(sourceFrame.headers().isEmpty()); + + sourceFrame.headers().set(StompHeaders.HOST, "localhost"); + + StompFrame copyFrame = sourceFrame.copy(); + + assertEquals(sourceFrame.headers(), copyFrame.headers()); + assertEquals(sourceFrame.content(), copyFrame.content()); + + AsciiString copyHeaderName = new AsciiString("foo"); + AsciiString copyHeaderValue = new AsciiString("bar"); + copyFrame.headers().set(copyHeaderName, copyHeaderValue); + + assertFalse(sourceFrame.headers().contains(copyHeaderName, copyHeaderValue)); + assertTrue(copyFrame.headers().contains(copyHeaderName, copyHeaderValue)); + + assertEquals(1, sourceFrame.headers().size()); + assertEquals(2, copyFrame.headers().size()); + assertNotEquals(sourceFrame.headers(), copyFrame.headers()); + + assertTrue(sourceFrame.release()); + assertTrue(copyFrame.release()); + } +}
val
val
"2018-01-23T11:34:28"
"2018-01-03T16:13:16Z"
amizurov
val
netty/netty/7583_7587
netty/netty
netty/netty/7583
netty/netty/7587
[ "timestamp(timedelta=86811.0, similarity=0.8799133035237494)" ]
46dac128f7472f264e3cb53e4d1fa40f6b043034
03c8c5b67a2d9ce62c7cd7974ca33bb4a675eeca
[ "Some notes..\r\n\r\nMight make more sense for io.netty.resolver.dns.DefaultDnsCache#get to return something like this to avoid concurrency issues with the list (in my experience exposing mutable data from a cache is a bad idea)..\r\n\r\n```java\r\n @Override\r\n public List<? extends DnsCacheEntry> get(String hostname, DnsRecord[] additionals) {\r\n checkNotNull(hostname, \"hostname\");\r\n if (!emptyAdditionals(additionals)) {\r\n return null;\r\n }\r\n return Collections.unmodifiableList(new ArrayList<DnsCacheEntry>(resolveCache.get(hostname)));\r\n }\r\n```\r\notherwise we probably need to add a double check in the sync block to io.netty.resolver.dns.DnsNameResolver#doResolveAllCached and io.netty.resolver.dns.DnsNameResolver#doResolveCached..\r\n\r\n```java\r\n private boolean doResolveCached(String hostname,\r\n DnsRecord[] additionals,\r\n Promise<InetAddress> promise,\r\n DnsCache resolveCache) {\r\n final List<? extends DnsCacheEntry> cachedEntries = resolveCache.get(hostname, additionals);\r\n if (cachedEntries == null || cachedEntries.isEmpty()) {\r\n return false;\r\n }\r\n\r\n InetAddress address = null;\r\n Throwable cause = null;\r\n synchronized (cachedEntries) {\r\n final int numEntries = cachedEntries.size();\r\n if (numEntries == 0) {\r\n return false;\r\n }\r\n...\r\n```", "cc @mrniko", "Fixed by https://github.com/netty/netty/pull/7584... return a new `ArrayList` will produce too much GC :(", "@normanmaurer yeah figured as much, that's why I also mentioned the double check on the size in the sync block.", "@normanmaurer thanks for the quick response!", "That said I think we may want to do something smarter in the long run. But I think the fix is ok for now.", "@johnou please check https://github.com/netty/netty/pull/7587 ... I think this is a more proper fix", "@normanmaurer : We are still experiencing this issue in netty 4.1.20 version.\r\n\r\n", "@sindhuvaidy - This is expected. The fix is included in 4.1.21. Please upgrade." ]
[ "Little cleaner and less boiler plate code if we assign the locks to final fields as suggested in the javadocs https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html\r\n\r\n```java\r\nprivate final Lock readLock = lock.readLock();\r\nprivate final Lock writeLock = lock.writeLock();\r\n```", "is the read lock necessary?", "Yes as we read the field... of we update it we use the write lock", "done", "since this class is trying to accommodate for concurrent access ... should this be in a loop until nothing is removed?", "nit: this condition will be enforced by the map, consider removing the redundant null check. Also if the map allows null this will just be a no-op.", "if this field is treated as copy on write ... can we just use a volatile and avoid the locking? this would make things much more clear because we let the list escape the lock above in `get()`.", "the list escapes the lock here which may violate what ever locking/synchronization enforced by this class internally.", "nit: share code with the previous method?", "move this into the conditional block where it is actually used. If the assertion is not there `get(0)` will throw, and we already check for `isEmpty()` above.", "move this into the conditional block where it is actually used. If the assertion is not there `get(0)` will throw, and we already check for `isEmpty()` above.", "Yeah I think this would work... Let me do this", "I think I would keep it for now to make it clear we not support null at all.", "not a blocker but the decision to \"not support null\" could be consolidated in a single place (where we add to `resolveCache`) instead of spread out throughout the code.", "`set` -> `super`?", "we haven't verified that `entry` is in the `entries` list and so do we need a special case for this condition here?", "Can we clarify assumptions here? If it is not likely we will find the element then it seems beneficial to iterate first, and then only allocate/copy if we find the element. if it is likely we will find the element then the current approach (always allocate/copy) seems reasonable.", "would it be better to handle this by checking `if (entries.size() == 1 && entry.get(0).equals(newEntry)) { swap with empty collection }`? or is it possible that `entries` may contain multiple elements which equal `entry`?", "does it ever make sense to return an empty list, as opposed to just null? if we return empty lists then conditionals tend to get more complicated (e.g. `if not empty and not null`), and the tests should likely be updated to reflect this too.", "@Scottmitch we should most likely find it. Thats why I choose the way I am doing it here.", "@Scottmitch it may be possible to have multiple entries so I think the way its handled now it more safe.", "@Scottmitch I was thinking about this and decided that it may be better to return an empty list mainly because we not state in the javadocs that we will ever return null from the `DnsCache` interface. ", "I think if its empty its safe to return just `false`.", "TIL: didn't know there is a constructor for this :)", "Please include comment with this rational.", "`DefaultDnsCacheEntry` doesn't implement `equals`, and on each `cache(..)` call a new element is created. Can you clarify under which conditions the `entries` array would contain the same element multiple times?", "We have been returning `null` so perhaps it is best to update the javadocs. `null` is part of the language and there is no reliable way to express a java 6 API which won't return null, which means folks have to `null` check anyways at runtime.", "the question was related to https://github.com/netty/netty/pull/7587#discussion_r162137171 below. I was wondering if this special case could be removed if we first search for an item and then allocate an entry / array copy around it. If we don't find the element we can bail without a special case for empty.", "@Scottmitch actually scratch this... you are right it cant happen.", "if it is \"very likely\" we will find the element should we create the `ArrayList` with `size - 1`?", "if `size == 1` and `!entries.get(0).equals(entry)` then we don't need to go to the else condition (which will allocate/copy for no reason).", "Now that we have a special check for `size == 1` before this conditional block executes ... is this ever possible?", "honestly I don't care too much but at the end it ay be just good to be safe and not sorry... allocating an array which has one element more then needed is preferred over a memory copy because we need to resize imho.", "no... let me remove it.", "yep we can just return false", "it looks like we should return `true` in an else condition? consider simplifying the code the control flow is easier to follow:\r\n\r\n```java\r\nreturn entries.get(0).equals(entry) && compareAndSet(entries, Collections.<DefaultDnsCacheEntry>emptyList());\r\n```", "fine with me ... just may be able to save some memory if its \"very likely\".", "doh! Yeah... let me do what you suggested. ", "Actually no... there was something else wrong.\r\n\r\nThis is correct:\r\n\r\n```java\r\n if (entries.get(0).equals(entry)) {\r\n // If the list is empty we just return early and so not allocate a new ArrayList.\r\n if (compareAndSet(entries, Collections.<DefaultDnsCacheEntry>emptyList())) {\r\n return false;\r\n } else {\r\n // try again as the CAS failed\r\n continue;\r\n }\r\n }\r\n return false;\r\n```\r\n\r\n@Scottmitch WDYT ?", "sorry this was not correct as well. Pushed a new version which should be correct", "Is NoSuchElementException possible here?" ]
"2018-01-16T11:39:19Z"
[ "defect" ]
io.netty.resolver.dns.DnsNameResolver#doResolveCached race condition
### Expected behavior No exception. ### Actual behavior ``` 2018-01-15 05:33:32,915 ERROR [Redisson-Epoll-1-15] (org.redisson.connection.DNSMonitor) Unable to resolve xxx.0001.use1.cache.amazonaws.com java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) ~[?:1.8.0_144] at java.util.ArrayList.get(ArrayList.java:429) ~[?:1.8.0_144] at io.netty.resolver.dns.DnsNameResolver.doResolveCached(DnsNameResolver.java:613) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.dns.DnsNameResolver.doResolve(DnsNameResolver.java:593) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.dns.DnsNameResolver.doResolve(DnsNameResolver.java:527) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.SimpleNameResolver.resolve(SimpleNameResolver.java:63) ~[netty-resolver-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:100) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:66) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.dns.InflightNameResolver.resolve(InflightNameResolver.java:51) ~[netty-resolver-dns-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:57) ~[netty-resolver-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:32) ~[netty-resolver-4.1.19.Final.jar:4.1.19.Final] at io.netty.resolver.AbstractAddressResolver.resolve(AbstractAddressResolver.java:108) ~[netty-resolver-4.1.19.Final.jar:4.1.19.Final] at org.redisson.connection.DNSMonitor$1.run(DNSMonitor.java:89) ~[redisson-3.5.7.jar:?] at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38) ~[netty-common-4.1.19.Final.jar:4.1.19.Final] ``` ### Steps to reproduce No reproducer. ### Minimal yet complete reproducer code (or URL to code) n/a ### Netty version 4.1.19.Final ### JVM version (e.g. `java -version`) java version "1.8.0_131" Java(TM) SE Runtime Environment (build 1.8.0_131-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode) ### OS version (e.g. `uname -a`)
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java" ]
[]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java index f2acd3fac76..2b3477bd381 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java @@ -23,11 +23,13 @@ import java.net.InetAddress; import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import static io.netty.util.internal.ObjectUtil.checkNotNull; import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero; @@ -39,8 +41,8 @@ @UnstableApi public class DefaultDnsCache implements DnsCache { - private final ConcurrentMap<String, List<DefaultDnsCacheEntry>> resolveCache = - PlatformDependent.newConcurrentHashMap(); + private final ConcurrentMap<String, Entries> resolveCache = PlatformDependent.newConcurrentHashMap(); + private final int minTtl; private final int maxTtl; private final int negativeTtl; @@ -97,28 +99,21 @@ public int negativeTtl() { @Override public void clear() { - for (Iterator<Map.Entry<String, List<DefaultDnsCacheEntry>>> i = resolveCache.entrySet().iterator(); - i.hasNext();) { - final Map.Entry<String, List<DefaultDnsCacheEntry>> e = i.next(); - i.remove(); - cancelExpiration(e.getValue()); + while (!resolveCache.isEmpty()) { + for (Iterator<Map.Entry<String, Entries>> i = resolveCache.entrySet().iterator(); i.hasNext();) { + Map.Entry<String, Entries> e = i.next(); + i.remove(); + + e.getValue().cancelExpiration(); + } } } @Override public boolean clear(String hostname) { checkNotNull(hostname, "hostname"); - boolean removed = false; - for (Iterator<Map.Entry<String, List<DefaultDnsCacheEntry>>> i = resolveCache.entrySet().iterator(); - i.hasNext();) { - final Map.Entry<String, List<DefaultDnsCacheEntry>> e = i.next(); - if (e.getKey().equals(hostname)) { - i.remove(); - cancelExpiration(e.getValue()); - removed = true; - } - } - return removed; + Entries entries = resolveCache.remove(hostname); + return entries != null && entries.cancelExpiration(); } private static boolean emptyAdditionals(DnsRecord[] additionals) { @@ -129,22 +124,11 @@ private static boolean emptyAdditionals(DnsRecord[] additionals) { public List<? extends DnsCacheEntry> get(String hostname, DnsRecord[] additionals) { checkNotNull(hostname, "hostname"); if (!emptyAdditionals(additionals)) { - return null; + return Collections.<DnsCacheEntry>emptyList(); } - return resolveCache.get(hostname); - } - private List<DefaultDnsCacheEntry> cachedEntries(String hostname) { - List<DefaultDnsCacheEntry> oldEntries = resolveCache.get(hostname); - final List<DefaultDnsCacheEntry> entries; - if (oldEntries == null) { - List<DefaultDnsCacheEntry> newEntries = new ArrayList<DefaultDnsCacheEntry>(8); - oldEntries = resolveCache.putIfAbsent(hostname, newEntries); - entries = oldEntries != null? oldEntries : newEntries; - } else { - entries = oldEntries; - } - return entries; + Entries entries = resolveCache.get(hostname); + return entries == null ? null : entries.get(); } @Override @@ -157,22 +141,7 @@ public DnsCacheEntry cache(String hostname, DnsRecord[] additionals, if (maxTtl == 0 || !emptyAdditionals(additionals)) { return e; } - final int ttl = Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)); - final List<DefaultDnsCacheEntry> entries = cachedEntries(hostname); - - synchronized (entries) { - if (!entries.isEmpty()) { - final DefaultDnsCacheEntry firstEntry = entries.get(0); - if (firstEntry.cause() != null) { - assert entries.size() == 1; - firstEntry.cancelExpiration(); - entries.clear(); - } - } - entries.add(e); - } - - scheduleCacheExpiration(entries, e, ttl, loop); + cache0(e, Math.max(minTtl, (int) Math.min(maxTtl, originalTtl)), loop); return e; } @@ -186,40 +155,34 @@ public DnsCacheEntry cache(String hostname, DnsRecord[] additionals, Throwable c if (negativeTtl == 0 || !emptyAdditionals(additionals)) { return e; } - final List<DefaultDnsCacheEntry> entries = cachedEntries(hostname); - - synchronized (entries) { - final int numEntries = entries.size(); - for (int i = 0; i < numEntries; i ++) { - entries.get(i).cancelExpiration(); - } - entries.clear(); - entries.add(e); - } - scheduleCacheExpiration(entries, e, negativeTtl, loop); + cache0(e, negativeTtl, loop); return e; } - private static void cancelExpiration(List<DefaultDnsCacheEntry> entries) { - final int numEntries = entries.size(); - for (int i = 0; i < numEntries; i++) { - entries.get(i).cancelExpiration(); + private void cache0(DefaultDnsCacheEntry e, int ttl, EventLoop loop) { + Entries entries = resolveCache.get(e.hostname()); + if (entries == null) { + entries = new Entries(e); + Entries oldEntries = resolveCache.putIfAbsent(e.hostname(), entries); + if (oldEntries != null) { + entries = oldEntries; + entries.add(e); + } } + + scheduleCacheExpiration(entries, e, ttl, loop); } - private void scheduleCacheExpiration(final List<DefaultDnsCacheEntry> entries, + private void scheduleCacheExpiration(final Entries entries, final DefaultDnsCacheEntry e, int ttl, EventLoop loop) { e.scheduleExpiration(loop, new Runnable() { @Override public void run() { - synchronized (entries) { - entries.remove(e); - if (entries.isEmpty()) { - resolveCache.remove(e.hostname()); - } + if (entries.remove(e)) { + resolveCache.remove(e.hostname); } } }, ttl, TimeUnit.SECONDS); @@ -289,4 +252,98 @@ public String toString() { } } } + + // Directly extend AtomicReference for intrinsics and also to keep memory overhead low. + private static final class Entries extends AtomicReference<List<DefaultDnsCacheEntry>> { + + Entries(DefaultDnsCacheEntry entry) { + super(Collections.singletonList(entry)); + } + + void add(DefaultDnsCacheEntry e) { + if (e.cause() == null) { + for (;;) { + List<DefaultDnsCacheEntry> entries = get(); + if (!entries.isEmpty()) { + final DefaultDnsCacheEntry firstEntry = entries.get(0); + if (firstEntry.cause() != null) { + assert entries.size() == 1; + if (compareAndSet(entries, Collections.singletonList(e))) { + firstEntry.cancelExpiration(); + return; + } else { + // Need to try again as CAS failed + continue; + } + } + // Create a new List for COW semantics + List<DefaultDnsCacheEntry> newEntries = new ArrayList<DefaultDnsCacheEntry>(entries.size() + 1); + newEntries.addAll(entries); + newEntries.add(e); + if (compareAndSet(entries, newEntries)) { + return; + } + } else if (compareAndSet(entries, Collections.singletonList(e))) { + return; + } + } + } else { + List<DefaultDnsCacheEntry> entries = getAndSet(Collections.singletonList(e)); + cancelExpiration(entries); + } + } + + boolean remove(DefaultDnsCacheEntry entry) { + for (;;) { + List<DefaultDnsCacheEntry> entries = get(); + int size = entries.size(); + if (size == 0) { + return false; + } else if (size == 1) { + if (entries.get(0).equals(entry)) { + // If the list is empty we just return early and so not allocate a new ArrayList. + if (compareAndSet(entries, Collections.<DefaultDnsCacheEntry>emptyList())) { + return true; + } + } else { + return false; + } + } else { + // Just size the new ArrayList as before as we may not find the entry we are looking for and not + // want to cause an extra allocation / memory copy in this case. + // + // Its very likely we find the entry we are looking for so we directly create a new ArrayList + // and fill it. + List<DefaultDnsCacheEntry> newEntries = new ArrayList<DefaultDnsCacheEntry>(size); + for (int i = 0; i < size; i++) { + DefaultDnsCacheEntry e = entries.get(i); + if (!e.equals(entry)) { + newEntries.add(e); + } + } + if (compareAndSet(entries, Collections.unmodifiableList(newEntries))) { + // This will return true if an entry was removed. + return newEntries.size() != size; + } + } + } + } + + boolean cancelExpiration() { + List<DefaultDnsCacheEntry> entries = getAndSet(Collections.<DefaultDnsCacheEntry>emptyList()); + if (entries.isEmpty()) { + return false; + } + + cancelExpiration(entries); + return true; + } + + private static void cancelExpiration(List<DefaultDnsCacheEntry> entryList) { + final int numEntries = entryList.size(); + for (int i = 0; i < numEntries; i++) { + entryList.get(i).cancelExpiration(); + } + } + } } diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java index 1a928f8c23b..eaa714026d2 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java @@ -600,43 +600,28 @@ private boolean doResolveCached(String hostname, Promise<InetAddress> promise, DnsCache resolveCache) { final List<? extends DnsCacheEntry> cachedEntries = resolveCache.get(hostname, additionals); - if (cachedEntries == null) { + if (cachedEntries == null || cachedEntries.isEmpty()) { return false; } - InetAddress address = null; - Throwable cause = null; - synchronized (cachedEntries) { + Throwable cause = cachedEntries.get(0).cause(); + if (cause == null) { final int numEntries = cachedEntries.size(); - if (numEntries == 0) { - return false; - } - - if (cachedEntries.get(0).cause() != null) { - cause = cachedEntries.get(0).cause(); - } else { - // Find the first entry with the preferred address type. - for (InternetProtocolFamily f : resolvedInternetProtocolFamilies) { - for (int i = 0; i < numEntries; i++) { - final DnsCacheEntry e = cachedEntries.get(i); - if (f.addressType().isInstance(e.address())) { - address = e.address(); - break; - } + // Find the first entry with the preferred address type. + for (InternetProtocolFamily f : resolvedInternetProtocolFamilies) { + for (int i = 0; i < numEntries; i++) { + final DnsCacheEntry e = cachedEntries.get(i); + if (f.addressType().isInstance(e.address())) { + trySuccess(promise, e.address()); + return true; } } } - } - - if (address != null) { - trySuccess(promise, address); - return true; - } - if (cause != null) { + return false; + } else { tryFailure(promise, cause); return true; } - return false; } private static <T> void trySuccess(Promise<T> promise, T result) { @@ -732,44 +717,34 @@ private boolean doResolveAllCached(String hostname, Promise<List<InetAddress>> promise, DnsCache resolveCache) { final List<? extends DnsCacheEntry> cachedEntries = resolveCache.get(hostname, additionals); - if (cachedEntries == null) { + if (cachedEntries == null || cachedEntries.isEmpty()) { return false; } - List<InetAddress> result = null; - Throwable cause = null; - synchronized (cachedEntries) { + Throwable cause = cachedEntries.get(0).cause(); + if (cause == null) { + List<InetAddress> result = null; final int numEntries = cachedEntries.size(); - if (numEntries == 0) { - return false; - } - - if (cachedEntries.get(0).cause() != null) { - cause = cachedEntries.get(0).cause(); - } else { - for (InternetProtocolFamily f : resolvedInternetProtocolFamilies) { - for (int i = 0; i < numEntries; i++) { - final DnsCacheEntry e = cachedEntries.get(i); - if (f.addressType().isInstance(e.address())) { - if (result == null) { - result = new ArrayList<InetAddress>(numEntries); - } - result.add(e.address()); + for (InternetProtocolFamily f : resolvedInternetProtocolFamilies) { + for (int i = 0; i < numEntries; i++) { + final DnsCacheEntry e = cachedEntries.get(i); + if (f.addressType().isInstance(e.address())) { + if (result == null) { + result = new ArrayList<InetAddress>(numEntries); } + result.add(e.address()); } } } - } - - if (result != null) { - trySuccess(promise, result); - return true; - } - if (cause != null) { + if (result != null) { + trySuccess(promise, result); + return true; + } + return false; + } else { tryFailure(promise, cause); return true; } - return false; } static final class ListResolverContext extends DnsNameResolverContext<List<InetAddress>> {
null
train
val
"2018-01-22T20:17:56"
"2018-01-15T12:02:48Z"
johnou
val
netty/netty/7585_7594
netty/netty
netty/netty/7585
netty/netty/7594
[ "timestamp(timedelta=33.0, similarity=1.0000000000000002)" ]
336bea9dc541413be4cd961417e2be456bdcac11
882c59c6aa6323236abb1a5bc18820b1feacf5e2
[ "Fixed by https://github.com/netty/netty/pull/7594 ... @asarkar PTAL", "Fixed by https://github.com/netty/netty/pull/7594" ]
[ "Consider merging this into one `RUN ... && \\ ...` command to have a single layer created for this group of operation that is logically related.", "Consider sorting and multi-lining for easier maintenance: https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#sort-multi-line-arguments", "I believe Google groups need sign up, right? If that's the case, consider using an email that a user of the image can contact without having to sign up for Google groups, all they want to do is report issues.", "This should be published to Docker Cloud, probably under `netty/netty-centos6`. Then CI build changed to run the following line (`docker run ...`).", "I suggest starting from OpenJDK base image, so that you don't have to do the install yourself.\r\nhttps://hub.docker.com/r/library/openjdk/tags/", "I don't see Maven used anywhere, it has to be put on the path. Here's how to do that:\r\n```\r\ncurl -sSL http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xz && \\\r\nln -sf $(pwd)/apache-maven-$MAVEN_VERSION $(pwd)/maven && \\\r\nln -sf $(pwd)/maven/bin/mvn /usr/local/bin/mvn && \\\r\nfind maven/bin -type f -name \"*.cmd\" -exec rm -f {} +\r\n```", "no you can send an email to it even without sign up.", "we need to ensure we use centos6 so the native stuff is build against the correct GLIBC version etc. ", "I see, that's why I couldn't get it working on Debian. This PR is going to make life easier for a lot of people.", "It's defined in PATH below. " ]
"2018-01-18T15:23:16Z"
[ "improvement", "feature" ]
Provide a Docker image for reproducible builds
### Expected behavior Developer can build on any platform using a Docker image without having to install additional native packages. Simply cloning the repo and following an one-liner build command should be enough. We should provide a fully-configured Docker image, and also configure the TeamCity CI to use it (I hope it has support for Docker). That way, every build will be reproducible without the million variables that are involved today (OS, OS version, Linux distro, package version, Maven version, etc etc). FWIW, the Maven version dependency will be eliminated with this PR https://github.com/netty/netty/issues/7578 Sample build command: ``` docker run -it -v /path/to/local/repo:/home/netty/netty netty/netty-build ``` The above command assumes that the default entrypoint to the Docker image is `mvn -f /home/netty/netty clean install`. Of course, the actual path and the build commands can vary, I just made these up. ### Actual behavior Build is pretty much wild west. For building on Linux, additional native packages need to be installed. Haven't tried on Windows, but I couldn't get it working on a Mac using a Debian VM or Docker image as it kept running OOM. I don't accept having to install a bunch of additional packages on my system for various reasons, security being an obvious one. ### Steps to reproduce Clone the repo and run `mvn clean install`. Watch it fail. ### Minimal yet complete reproducer code (or URL to code) N/A ### Netty version N/A ### JVM version (e.g. `java -version`) N/A ### OS version (e.g. `uname -a`) N/A
[]
[ "docker/Dockerfile-netty-centos6", "docker/README.md" ]
[]
diff --git a/docker/Dockerfile-netty-centos6 b/docker/Dockerfile-netty-centos6 new file mode 100644 index 00000000000..d6e2339f510 --- /dev/null +++ b/docker/Dockerfile-netty-centos6 @@ -0,0 +1,34 @@ +FROM centos:6 +MAINTAINER netty@googlegroups.com +ENTRYPOINT /bin/bash + +ENV SOURCE_DIR $HOME/source +ENV MAVEN_VERSION 3.5.2 +ENV JAVA_VERSION 1.8.0 + +RUN mkdir $SOURCE_DIR +WORKDIR $SOURCE_DIR + +# install dependencies +RUN yum install -y \ + apr-devel \ + autoconf \ + automake \ + git \ + glibc-devel \ + java-$JAVA_VERSION-openjdk-devel \ + libtool \ + lksctp-tools \ + lsb-core \ + make \ + openssl-devel \ + tar \ + wget + + +RUN wget -q http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz && tar xfz apache-maven-$MAVEN_VERSION-bin.tar.gz && mv apache-maven-$MAVEN_VERSION /opt/ + +RUN echo 'PATH=/opt/apache-maven-$MAVEN_VERSION/bin:$PATH' >> ~/.bashrc +RUN echo 'export JAVA_HOME="/usr/lib/jvm/java-$JAVA_VERSION/"' >> ~/.bashrc + +RUN rm -rf $SOURCE_DIR diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 00000000000..157236f5bba --- /dev/null +++ b/docker/README.md @@ -0,0 +1,15 @@ + +** Create a docker image ** +``` +docker build -f Dockerfile-netty-centos6 . -t netty-centos6 +``` + +** Using the image ** + +``` +cd /path/to/netty/ +``` + +``` +docker run -it -v ~/.m2:/root/.m2 -v ~/.ssh:/root/.ssh -v ~/.gnupg:/root/.gnupg -v `pwd`:/code -w /code netty-centos6 bash +```
null
train
val
"2018-01-22T19:50:08"
"2018-01-16T01:27:44Z"
asarkar
val
netty/netty/7607_7612
netty/netty
netty/netty/7607
netty/netty/7612
[ "timestamp(timedelta=0.0, similarity=0.8693949310932216)" ]
27ff15319c2e566c44e333b9bd59cf210c130c2f
8a095d0244da237f6eb76c4c24be49a1833b3988
[ "Test case\r\n```java\r\n@Test\r\n public void freesPingFrames() {\r\n ByteBuf content = UnpooledByteBufAllocator.DEFAULT.buffer(8).writeLong(0);\r\n DefaultHttp2PingFrame frame = new DefaultHttp2PingFrame(content);\r\n assertEquals(1, content.refCnt());\r\n codec.onHttp2Frame(frame);\r\n assertEquals(0, content.refCnt());\r\n }\r\n```\r\n posted [here](https://github.com/bryce-anderson/netty/commit/37cdcd4defa853e5b9883c9bbea60e91a72ac5c6#diff-da759abb652d5db65698f9baf72b9ed2) results in\r\n```\r\njava.lang.AssertionError: \r\nExpected :0\r\nActual :1\r\n\r\nio.netty.handler.codec.http2.Http2MultiplexCodecTest.freesPingFrames(Http2MultiplexCodecTest.java:134)\r\n```", "If I can get someone to sanity check my results, this the fix is trivial and I'm happy to do it.", "Your assessment seems correct to me. It has been a while but I think the though process at the time was \"we aren't sure if the user will need to care about ping (or ping ack) yet so lets drop it\". However we retain the `ByteBuf` so that approach is inconsistent. My vote would be to propagate this through the parent channel's pipeline (as a channel read) so the user has visibility into it (instead of just releasing it as suggested in your unit test above). If the user doesn't handle it then it will automatically be released at the tail of the pipeline and a message will be logged (just like usual). @ejona86 @normanmaurer @carl-mastrangelo - WDYT?", "Note that users can also intercept these messages via wrapping the `FrameListener`, although that's a bit intricate to setup.", "`codec-http2` currently has two flavors of APIs:\r\n- `Http2ConnectionHandler` and `FrameListener` - the initial API, lots of hours/usage on this code, low object allocation, not canonical Netty design (extensibility via the channel pipeline is challenging)\r\n- `Http2FrameCodec` and `Http2MultiplexCodec` - new API design which is more canonical Netty, more object allocation, not as much hours/usage (thus \"simple\" bugs like this).\r\n\r\nWe try to minimize how much of the `FrameListener` API is exposed from the `Http2MultiplexCodec` and ideally its usage of the `FrameListener` is an implementation detail.", "I think what @Scottmitch proposes makes sense here. @bryce-anderson please go ahead and implement it or let us know if you have no time and we should do once we have cycles. ", "PR submitted. https://github.com/netty/netty/pull/7612\r\n\r\nI suppose having a downstream handler gives the user a vector for sending and receiving pings so propagating unhandled frames downstream seems right to me too unless you have plans to offer a first class API for pings.", "> unless you have plans to offer a first class API for pings.\r\n\r\nThe API would be object propagation through the pipeline (just like most other Netty codecs) so I think we are good here.", "It seems there's a general problem with Http2MultiplexCodec: it should either release or propagate unknown types. That's what #7612 does. So I'm good with that PR.\r\n\r\nHowever, I don't think we actually want to propagate PINGs, or at least in that way.\r\n\r\nI'd suggest two options:\r\n1. Don't propagate inbound PINGs. Instead, let an outbound PING have a Future that will be completed when the PING ACK arrives. The payload of PING wouldn't be exposed at all. (If we separated Http2MultiplexCodec from Http2FrameCodec we could propagate the PING within that small area, but that doesn't exist today. This is why PING existed during my earlier h2childchan PRs.)\r\n2. Use a userEvent. I don't like propagating the read because the logging isn't really acceptable. As a user you're forced to handle it. Yes, it will be \"handled\" without you doing anything, but the logging just tells you \"you're doing it wrong.\" That's the approach I was taking for the child chan itself; everything optional is a user event or has a trigger to enable.\r\n\r\nFor (2), if we're going to expose the payload, let's use a simple long or byte[] instead of ByteBuf. The size of the payload is fixed and really small. There's really no gain by using ByteBuf and the refcounting complicates things. This is the same approach I want to make for Http2GoAwayFrame. It is sort of \"neither here nor there\" for how we handle PING, though.", "> Don't propagate inbound PINGs. Instead, let an outbound PING have a Future that will be completed when the PING ACK arrives.\r\n\r\nThis is not consistent with Netty APIs which typically don't cater to request/response based APIs and instead rely upon the pipeline to propagate data. Since one of the primary goals of the child channel API is to be consistent/canonical with Netty I would suggest we stick with the pipeline approach. Higher layers can build a promise based notification system if that is desired.\r\n\r\n> Use a userEvent.\r\n\r\nThe primary motivation for these seems to be \"the logging at the tail of the pipeline maybe noisy\". If this is the case I would prefer to stick with the \"channelRead\" because it seems more semantically correct. PING is a data event defined by the protocol, where as userEvents are primarily to propagate control messages between handlers in the pipeline. We can always [override the pipeline behavior](https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java#L1194) to avoid logging in scenarios that are \"safe\" to ignore.\r\n\r\n> For (2), if we're going to expose the payload, let's use a simple long or byte[] instead of ByteBuf. \r\n\r\nMy main hesitation here is copying when it may otherwise not be necessary. Agreed that refcounting increases complexity, but that is not newly introduced here and is wide spread in Netty. I'm not strongly opposed but using ByteBuf is common practice in Netty and can avoid memory copies when folks may not otherwise even care about the payload content, or can immediately discard (e.g. release) it.", "> This is not consistent with Netty APIs which typically don't cater to request/response based APIs and instead rely upon the pipeline to propagate data.\r\n\r\nThere was another reason I was doing it: to manage allocating of PING ids. The payload is frequently an ID to keep easier track of what the ACKs mean. Coordinating the allocation is a bit of a problem since there are multiple handlers (including the HTTP/2 code itself) that may need to send them. Normally in Netty there's no need for coordination.\r\n\r\n> We can always override the pipeline behavior to avoid logging in scenarios that are \"safe\" to ignore.\r\n\r\nWait... it's a logger.debug... that's completely fine. And it's been that way... \"forever\". Now I wonder what in the world I was seeing...\r\n\r\nLuckily I don't think that changes my design of the child channels.\r\n\r\n> My main hesitation here is copying when it may otherwise not be necessary.\r\n\r\nCopying _8_ bytes? The ByteBuf pointer chasing and vtable indirection will be much more costly than that. And a pointer is 8 bytes, so we're _already_ copying the equivalent amount of data. And a pointer assignment is also more expensive in Java to coordinate with the GC. The ByteBuf will also need read and write indexes and a capacity and ref counting and...\r\n\r\nThe copying could be a bigger concern for GOAWAY, but the messages tend to be short. (I've not seen one larger than, say, 16 bytes?) But the GOAWAY case is also the one that benefits the most, in that [we're duplicating a DefaultHttp2GoAwayFrame and a ByteBuf for each child channel](https://github.com/netty/netty/blob/911b2ac/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java#L326). That's (8+4+4)+(8+4+4+4+4+4) = 44 bytes (assuming a DuplicatedByteBuf). If we used a byte[], we could actually share the same DefaultHttp2GoAwayFrame across all child channels, because there's no longer the readerIndex.\r\n\r\nTo me, the argument for keeping it as a ByteBuf is that it is convenient, because people are familiar with working with them.", "Agreed `ByteBuf` currently has a high constant overhead and is bloated for small payloads (which is exacerbated by duplication/wrapping). Good point about the payload size. Even if its a few hundred bytes (GOAWAY debug information) it is likely a rare occurrence and may not be worth the extra complexity. I think the main selling point would be consistency, but I agree it doesn't seem worth it. @normanmaurer - WDYT?\r\n\r\n> we could actually share the same DefaultHttp2GoAwayFrame across all child channels, because there's no longer the readerIndex.\r\n\r\nSharing should be possible either way, no? Just with `ByteBuf` it requires reference count management and may not incur framing overhead (copy from byte[] to the frame to write).", "> Sharing should be possible either way, no?\r\n\r\nNo... :''( . If one child channel reads the ByteBuf, then the readerIndex will be changed for all the child channels. So only the first reader gets to see what's inside, unless all readers make sure to avoid updating the readerIndex.", "> If one child channel reads the ByteBuf\r\n\r\nSo there are 2 concerns:\r\n\r\n- reference counting. we should be able to manage via `retain`/`release`.\r\n- reader/writer indexes. we should be able to use `duplicate()`/`slice()`.\r\n\r\nDoes this make sense? This is the design of the `ByteBuf` API and not necessarily new here. Not saying its what we want todo, but its an option IIUC.", "lets continue discussion in https://github.com/netty/netty/issues/7629" ]
[ "btw, do you need to free this content?", "Do you mean for the test, or for the `Http2MultiplexedCodec`?", "It doesn't look like it's released. It should be. That's why the CI test fails with \"Build failure on specific text in build log: Resource leak detected\".", "IIUC we need a `decodedFrame.release();` after the assert.", "Should be fixed now.", "you need to call `receivedPing.release()` as well to ensure we not leak. This way the CI will also pass.", "I think you might have been looking at an outdated PR: it's released on line 181 and tests are green.", "yep seems so :D all good..." ]
"2018-01-23T15:33:59Z"
[ "defect" ]
Http2MultiplexCodec leaks ping payloads
### Expected behavior The payload of a PingFrame would be released or passed somewhere into the application for consumption. ### Actual behavior It appears that `Http2PingFrame`s are dropped on the floor in the [`Http2MultiplexCodec.onHttp2Frame`](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java#L219) method. ### Steps to reproduce Start HTTP/2 server and send it ping frames with advanced leak detection yields logs as follows: ``` 2018-01-22 22:46:25,178 ERR i.n.u.ResourceLeakDetector | LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information. Recent access records: 16 #16: io.netty.util.ReferenceCountUtil.release(ReferenceCountUtil.java:84) io.netty.util.ReferenceCountUtil.safeRelease(ReferenceCountUtil.java:109) io.netty.channel.ChannelOutboundBuffer.remove(ChannelOutboundBuffer.java:256) io.netty.channel.ChannelOutboundBuffer.removeBytes(ChannelOutboundBuffer.java:337) io.netty.channel.epoll.AbstractEpollStreamChannel.writeBytesMultiple(AbstractEpollStreamChannel.java:302) io.netty.channel.epoll.AbstractEpollStreamChannel.doWriteMultiple(AbstractEpollStreamChannel.java:505) io.netty.channel.epoll.AbstractEpollStreamChannel.doWrite(AbstractEpollStreamChannel.java:442) io.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:934) io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.flush0(AbstractEpollChannel.java:543) io.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:901) io.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1321) io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) io.netty.channel.ChannelDuplexHandler.flush(ChannelDuplexHandler.java:117) io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) io.netty.handler.codec.http2.Http2ConnectionHandler.flush(Http2ConnectionHandler.java:201) io.netty.handler.codec.http2.Http2MultiplexCodec.flush(Http2MultiplexCodec.java:373) io.netty.handler.codec.http2.Http2MultiplexCodec.flush0(Http2MultiplexCodec.java:378) io.netty.handler.codec.http2.Http2MultiplexCodec.onChannelReadComplete(Http2MultiplexCodec.java:366) io.netty.handler.codec.http2.Http2MultiplexCodec.channelReadComplete(Http2MultiplexCodec.java:340) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete(AbstractChannelHandlerContext.java:373) io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(ChannelInboundHandlerAdapter.java:97) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete(AbstractChannelHandlerContext.java:373) io.netty.channel.DefaultChannelPipeline$HeadContext.channelReadComplete(DefaultChannelPipeline.java:1364) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.DefaultChannelPipeline.fireChannelReadComplete(DefaultChannelPipeline.java:941) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:817) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #15: io.netty.buffer.AdvancedLeakAwareByteBuf.nioBufferCount(AdvancedLeakAwareByteBuf.java:702) io.netty.channel.unix.IovArray.add(IovArray.java:79) io.netty.channel.unix.IovArray.processMessage(IovArray.java:209) io.netty.channel.ChannelOutboundBuffer.forEachFlushedMessage(ChannelOutboundBuffer.java:738) io.netty.channel.epoll.AbstractEpollStreamChannel.doWriteMultiple(AbstractEpollStreamChannel.java:500) io.netty.channel.epoll.AbstractEpollStreamChannel.doWrite(AbstractEpollStreamChannel.java:442) io.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:934) io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.flush0(AbstractEpollChannel.java:543) io.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:901) io.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1321) io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) io.netty.channel.ChannelDuplexHandler.flush(ChannelDuplexHandler.java:117) io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) io.netty.handler.codec.http2.Http2ConnectionHandler.flush(Http2ConnectionHandler.java:201) io.netty.handler.codec.http2.Http2MultiplexCodec.flush(Http2MultiplexCodec.java:373) io.netty.handler.codec.http2.Http2MultiplexCodec.flush0(Http2MultiplexCodec.java:378) io.netty.handler.codec.http2.Http2MultiplexCodec.onChannelReadComplete(Http2MultiplexCodec.java:366) io.netty.handler.codec.http2.Http2MultiplexCodec.channelReadComplete(Http2MultiplexCodec.java:340) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete(AbstractChannelHandlerContext.java:373) io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(ChannelInboundHandlerAdapter.java:97) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete(AbstractChannelHandlerContext.java:373) io.netty.channel.DefaultChannelPipeline$HeadContext.channelReadComplete(DefaultChannelPipeline.java:1364) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:398) io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(AbstractChannelHandlerContext.java:380) io.netty.channel.DefaultChannelPipeline.fireChannelReadComplete(DefaultChannelPipeline.java:941) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:817) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #14: io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:273) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #13: io.netty.buffer.DefaultByteBufHolder.retain(DefaultByteBufHolder.java:93) io.netty.handler.codec.http2.DefaultHttp2PingFrame.retain(DefaultHttp2PingFrame.java:76) io.netty.handler.codec.http2.Http2FrameCodec$FrameListener.onPingRead(Http2FrameCodec.java:488) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onPingRead(DefaultHttp2ConnectionDecoder.java:432) io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onPingRead(Http2InboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPingFrame(DefaultHttp2FrameReader.java:583) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:269) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #12: Hint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point. io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:116) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723) io.netty.channel.ChannelDuplexHandler.write(ChannelDuplexHandler.java:106) com.twitter.finagle.netty4.channel.ChannelStatsHandler.write(ChannelStatsHandler.scala:96) io.netty.channel.AbstractChannelHandlerContext.invokeWrite0(AbstractChannelHandlerContext.java:738) io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:730) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:816) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723) io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writePing(DefaultHttp2FrameWriter.java:281) io.netty.handler.codec.http2.Http2OutboundFrameLogger.writePing(Http2OutboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writePing(DefaultHttp2ConnectionEncoder.java:269) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onPingRead(DefaultHttp2ConnectionDecoder.java:430) io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onPingRead(Http2InboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPingFrame(DefaultHttp2FrameReader.java:583) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:269) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #11: Hint: 'channelStats' will handle the message from this point. io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:116) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:810) io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:723) io.netty.handler.codec.http2.DefaultHttp2FrameWriter.writePing(DefaultHttp2FrameWriter.java:281) io.netty.handler.codec.http2.Http2OutboundFrameLogger.writePing(Http2OutboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder.writePing(DefaultHttp2ConnectionEncoder.java:269) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onPingRead(DefaultHttp2ConnectionDecoder.java:430) io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onPingRead(Http2InboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPingFrame(DefaultHttp2FrameReader.java:583) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:269) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #10: io.netty.buffer.AdvancedLeakAwareByteBuf.retainedSlice(AdvancedLeakAwareByteBuf.java:84) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder$FrameReadListener.onPingRead(DefaultHttp2ConnectionDecoder.java:430) io.netty.handler.codec.http2.Http2InboundFrameLogger$1.onPingRead(Http2InboundFrameLogger.java:99) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPingFrame(DefaultHttp2FrameReader.java:583) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:269) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #9: io.netty.buffer.AdvancedLeakAwareByteBuf.readSlice(AdvancedLeakAwareByteBuf.java:114) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readPingFrame(DefaultHttp2FrameReader.java:579) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:269) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #8: io.netty.buffer.AdvancedLeakAwareByteBuf.readSlice(AdvancedLeakAwareByteBuf.java:114) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processPayloadState(DefaultHttp2FrameReader.java:243) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:160) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #7: io.netty.buffer.AdvancedLeakAwareByteBuf.readInt(AdvancedLeakAwareByteBuf.java:432) io.netty.handler.codec.http2.Http2CodecUtil.readUnsignedInt(Http2CodecUtil.java:210) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processHeaderState(DefaultHttp2FrameReader.java:192) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:148) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #6: io.netty.buffer.AdvancedLeakAwareByteBuf.readUnsignedByte(AdvancedLeakAwareByteBuf.java:402) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processHeaderState(DefaultHttp2FrameReader.java:191) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:148) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #5: io.netty.buffer.AdvancedLeakAwareByteBuf.readByte(AdvancedLeakAwareByteBuf.java:396) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processHeaderState(DefaultHttp2FrameReader.java:190) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:148) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #4: io.netty.buffer.AdvancedLeakAwareByteBuf.readUnsignedMedium(AdvancedLeakAwareByteBuf.java:426) io.netty.handler.codec.http2.DefaultHttp2FrameReader.processHeaderState(DefaultHttp2FrameReader.java:185) io.netty.handler.codec.http2.DefaultHttp2FrameReader.readFrame(DefaultHttp2FrameReader.java:148) io.netty.handler.codec.http2.Http2InboundFrameLogger.readFrame(Http2InboundFrameLogger.java:41) io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder.decodeFrame(DefaultHttp2ConnectionDecoder.java:118) io.netty.handler.codec.http2.Http2ConnectionHandler$FrameDecoder.decode(Http2ConnectionHandler.java:383) io.netty.handler.codec.http2.Http2ConnectionHandler.decode(Http2ConnectionHandler.java:443) io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489) io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #3: Hint: 'UpgradeMultiplexCodecBuilder$$anon$1#0' will handle the message from this point. io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:116) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86) com.twitter.finagle.netty4.channel.ChannelStatsHandler.channelRead(ChannelStatsHandler.scala:108) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #2: Hint: 'channelStats' will handle the message from this point. io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:116) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340) io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1359) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) #1: Hint: 'DefaultChannelPipeline$HeadContext#0' will handle the message from this point. io.netty.channel.DefaultChannelPipeline.touch(DefaultChannelPipeline.java:116) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:345) io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:935) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:797) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) Created at: io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:331) io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:181) io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:172) io.netty.buffer.AbstractByteBufAllocator.ioBuffer(AbstractByteBufAllocator.java:133) io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator$MaxMessageHandle.allocate(DefaultMaxMessagesRecvByteBufAllocator.java:80) io.netty.channel.epoll.EpollRecvByteAllocatorHandle.allocate(EpollRecvByteAllocatorHandle.java:71) io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:786) io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:404) io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:304) io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) com.twitter.finagle.util.BlockingTimeTrackingThreadFactory$$anon$1.run(BlockingTimeTrackingThreadFactory.scala:23) java.lang.Thread.run(Thread.java:748) ``` ### Netty version 4.1.16, though a scan of the GitHub repo suggests it's still an issue. ### JVM version (e.g. `java -version`) openjdk version "1.8.0_152" ### OS version (e.g. `uname -a`) Centos 7
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java index ae98bfea08b..aeeec3feb68 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java @@ -227,6 +227,9 @@ final void onHttp2Frame(ChannelHandlerContext ctx, Http2Frame frame) { if (settings.initialWindowSize() != null) { initialOutboundStreamWindow = settings.initialWindowSize(); } + } else { + // Send any other frames down the pipeline + ctx.fireChannelRead(frame); } }
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java index ecdcdcf7c85..bec5cd964ee 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java @@ -170,6 +170,17 @@ public void inboundDataFrameShouldEmitWindowUpdateFrame() { verifyFramesMultiplexedToCorrectChannel(inboundStream, inboundHandler, 2); } + @Test + public void unhandledHttp2FramesShouldBePropagated() { + ByteBuf content = UnpooledByteBufAllocator.DEFAULT.buffer(8).writeLong(0); + Http2PingFrame decodedFrame = new DefaultHttp2PingFrame(content); + + codec.onHttp2Frame(decodedFrame); + Http2PingFrame receivedPing = parentChannel.readInbound(); + assertSame(receivedPing, decodedFrame); + assertTrue(receivedPing.release()); + } + @Test public void channelReadShouldRespectAutoRead() { LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream);
test
val
"2018-01-23T15:27:57"
"2018-01-23T00:07:55Z"
bryce-anderson
val
netty/netty/7620_7622
netty/netty
netty/netty/7620
netty/netty/7622
[ "timestamp(timedelta=14.0, similarity=0.9017916825519452)" ]
4921f62c8ab8205fd222439dcd1811760b05daf1
688c0ca551a2486c38ced56baa23d41a712ab8c2
[ "```\r\nprivate static String[] splitMultipartHeader(String sb) {\r\n ...\r\n valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd);\r\n valueEnd = HttpPostBodyUtil.findEndOfString(sb);\r\n headers.add(sb.substring(nameStart, nameEnd));\r\n\r\n String svalue = sb.substring(valueStart, valueEnd); // <--- StringIndexOutOfBoundsException\r\n ...\r\n```\r\n\r\n```\r\nsplitMultipartHeader(\"Content-Type:\") -> valueStart=13 valueEnd=13 (OK returns [Content-Type, ])\r\nsplitMultipartHeader(\"Content-Type: \") -> valueStart=14 valueEnd=13\r\nsplitMultipartHeader(\"Content-Type: \\r\\n\") -> valueStart=16 valueEnd=13\r\n```", "Maybe you can provide a unit test and fix ?\n\n2018-01-24 18:54 GMT+01:00 Matteo Bertozzi <notifications@github.com>:\n\n> private static String[] splitMultipartHeader(String sb) {\n> ...\n> valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd);\n> valueEnd = HttpPostBodyUtil.findEndOfString(sb);\n> headers.add(sb.substring(nameStart, nameEnd));\n>\n> String svalue = sb.substring(valueStart, valueEnd); // <--- StringIndexOutOfBoundsException\n> ...\n>\n> splitMultipartHeader(\"Content-Type:\") -> valueStart=13 valueEnd=13\n> splitMultipartHeader(\"Content-Type: \") -> valueStart=14 valueEnd=13\n> splitMultipartHeader(\"Content-Type: \\r\\n\") -> valueStart=16 valueEnd=13\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/netty/netty/issues/7620#issuecomment-360218651>, or mute\n> the thread\n> <https://github.com/notifications/unsubscribe-auth/AAa0Qn1wYrWco54QVlb73vmnkCjaPl2yks5tN25igaJpZM4Rri_n>\n> .\n>\n", "https://gist.github.com/matteobertozzi/86e1b7d5f4205beee243897050a47069", "@matteobertozzi can you open a PR against 4.1 ?", "Fixed by https://github.com/netty/netty/pull/7622" ]
[ "@matteobertozzi should we just make this `StringUtil.EMPTY_STRING` when `valueStart >= valueEnd` ?\r\n\r\nSo something like this:\r\n\r\n```\r\nString svalue == valueStart >= valueEnd ? StringUtil.EMPTY_STRING : sb.substring(valueStart, valueEnd))\r\n```\r\nWDYT ?", "yeah, that's better", "@matteobertozzi please adjust and push." ]
"2018-01-24T22:04:48Z"
[]
HttpPostMultipartRequestDecoder.splitMultipartHeader() String index out of range: -1 with empty Content-Type
Parsing a multi-part request with an empty content type header: e.g. "Content-Type: " will produce a java.lang.StringIndexOutOfBoundsException: String index out of range: -1 ``` java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1967) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.splitMultipartHeader(HttpPostMultipartRequestDecoder.java:1470) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.findMultipartDisposition(HttpPostMultipartRequestDecoder.java:680) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.decodeMultipart(HttpPostMultipartRequestDecoder.java:490) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.findMultipartDelimiter(HttpPostMultipartRequestDecoder.java:642) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.decodeMultipart(HttpPostMultipartRequestDecoder.java:477) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.parseBodyMultipart(HttpPostMultipartRequestDecoder.java:448) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.parseBody(HttpPostMultipartRequestDecoder.java:411) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.offer(HttpPostMultipartRequestDecoder.java:336) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.<init>(HttpPostMultipartRequestDecoder.java:185) at io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder.<init>(HttpPostMultipartRequestDecoder.java:142) ```
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java index 44b2641c6a4..8e3a90c009b 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostMultipartRequestDecoder.java @@ -1467,7 +1467,7 @@ private static String[] splitMultipartHeader(String sb) { valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd); valueEnd = HttpPostBodyUtil.findEndOfString(sb); headers.add(sb.substring(nameStart, nameEnd)); - String svalue = sb.substring(valueStart, valueEnd); + String svalue = (valueStart >= valueEnd) ? StringUtil.EMPTY_STRING : sb.substring(valueStart, valueEnd); String[] values; if (svalue.indexOf(';') >= 0) { values = splitMultipartHeaderValues(svalue);
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoderTest.java index 31e786a38c3..f8b756ca70a 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/multipart/HttpPostRequestDecoderTest.java @@ -626,4 +626,34 @@ public void testDecodeMalformedBadCharsetContentDispositionFieldParameters() thr req.release(); } } + + // https://github.com/netty/netty/issues/7620 + @Test + public void testDecodeMalformedEmptyContentTypeFieldParameters() throws Exception { + final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; + final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, + "http://localhost"); + req.headers().add(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); + // Force to use memory-based data. + final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); + final String data = "asdf"; + final String filename = "tmp-0.txt"; + final String body = + "--" + boundary + "\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n" + + "Content-Type: \r\n" + + "\r\n" + + data + "\r\n" + + "--" + boundary + "--\r\n"; + + req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8.name())); + // Create decoder instance to test. + final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req); + assertFalse(decoder.getBodyHttpDatas().isEmpty()); + InterfaceHttpData part1 = decoder.getBodyHttpDatas().get(0); + assertTrue(part1 instanceof FileUpload); + FileUpload fileUpload = (FileUpload) part1; + assertEquals("tmp-0.txt", fileUpload.getFilename()); + decoder.destroy(); + } }
test
val
"2018-01-25T07:01:52"
"2018-01-24T16:35:32Z"
matteobertozzi
val
netty/netty/7609_7624
netty/netty
netty/netty/7609
netty/netty/7624
[ "timestamp(timedelta=444.0, similarity=0.9133649548851649)" ]
b769ec09346e227b9e33d581f26e2cb0b22911a7
e1386713560a70218fc34f65e345abff491a4bed
[ "@laosijikaichele PRs welcome... that said I am not sure if we need anything here as `mayInterruptIfRunning` already signals that it may interrupt or not.", "I am setting up the netty development environment, after that, I will try a PR for this doc issue. :)", "Fixed by https://github.com/netty/netty/pull/7624" ]
[ "at a minimum we need {@inheritDoc}, and in general I'm not convinced this change is necessary as the `cancel` operation itself is indicated as best effort in the original javadocs and therefore the parameter may not be used in general.", "if a param value does not used in the method, then it should be indicated by the javadoc, but the original javadoc from `java.util.concurrent.Future#cancel` does not clearly indicate it, so the JVM team itself indicate it when the implementation method does not use the param `mayInterruptIfRunning`, please refer the javadoc of `java.util.concurrent.CompletableFuture#cancel` and `java.util.concurrent.ForkJoinTask#cancel` ;\r\n which javadocs clearly indicate that `mayInterruptIfRunning` has no effect in the implementation.", "@laosijikaichele actually I think this is not correct as it just delegates it and if it is ignored or not depends on the implementation of `delegate`", "@normanmaurer agree,I deleted javadoc for this method." ]
"2018-01-25T03:32:48Z"
[ "documentation" ]
should add java-doc for method DefaultPromise#cancel(boolean mayInterruptIfRunning)
### Expected behavior implementation of method `io.netty.util.concurrent.DefaultPromise#cancel(boolean mayInterruptIfRunning)` actually ignored the param `mayInterruptIfRunning`. so it need to make a comment like following: (this comment is copied from `java.util.concurrent.CompletableFuture#cancel`): > * @param mayInterruptIfRunning this value has no effect in this > * implementation because interrupts are not used to control > * processing. the other method `io.netty.util.concurrent.CompleteFuture#cancel` may do the same too. ### Actual behavior there is no comment about the param `mayInterruptIfRunning`, which will make user confusing when call the `cancel` method with a param `mayInterruptIfRunning`. ### Netty version 4
[ "common/src/main/java/io/netty/util/concurrent/CompleteFuture.java", "common/src/main/java/io/netty/util/concurrent/DefaultPromise.java", "common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java", "transport/src/main/java/io/netty/channel/VoidChannelPromise.java", "transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java" ]
[ "common/src/main/java/io/netty/util/concurrent/CompleteFuture.java", "common/src/main/java/io/netty/util/concurrent/DefaultPromise.java", "common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java", "transport/src/main/java/io/netty/channel/VoidChannelPromise.java", "transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/concurrent/CompleteFuture.java b/common/src/main/java/io/netty/util/concurrent/CompleteFuture.java index 84376233dd3..ed5755f5727 100644 --- a/common/src/main/java/io/netty/util/concurrent/CompleteFuture.java +++ b/common/src/main/java/io/netty/util/concurrent/CompleteFuture.java @@ -140,6 +140,11 @@ public boolean isCancelled() { return false; } + /** + * {@inheritDoc} + * + * @param mayInterruptIfRunning this value has no effect in this implementation. + */ @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; diff --git a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java index 6b175b2e5a0..dc595cfa99a 100644 --- a/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java +++ b/common/src/main/java/io/netty/util/concurrent/DefaultPromise.java @@ -308,6 +308,11 @@ public V getNow() { return (V) result; } + /** + * {@inheritDoc} + * + * @param mayInterruptIfRunning this value has no effect in this implementation. + */ @Override public boolean cancel(boolean mayInterruptIfRunning) { if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) { diff --git a/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java b/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java index 05cba6b83ad..6043d6ffec0 100644 --- a/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java +++ b/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java @@ -151,6 +151,11 @@ public void run() { } } + /** + * {@inheritDoc} + * + * @param mayInterruptIfRunning this value has no effect in this implementation. + */ @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean canceled = super.cancel(mayInterruptIfRunning); diff --git a/transport/src/main/java/io/netty/channel/VoidChannelPromise.java b/transport/src/main/java/io/netty/channel/VoidChannelPromise.java index be28f75db38..5aa61cd1332 100644 --- a/transport/src/main/java/io/netty/channel/VoidChannelPromise.java +++ b/transport/src/main/java/io/netty/channel/VoidChannelPromise.java @@ -166,6 +166,11 @@ public boolean tryFailure(Throwable cause) { return false; } + /** + * {@inheritDoc} + * + * @param mayInterruptIfRunning this value has no effect in this implementation. + */ @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; diff --git a/transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java b/transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java index e8fa84266b4..740ac337022 100644 --- a/transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java +++ b/transport/src/main/java/io/netty/channel/group/VoidChannelGroupFuture.java @@ -138,6 +138,11 @@ public Void getNow() { return null; } + /** + * {@inheritDoc} + * + * @param mayInterruptIfRunning this value has no effect in this implementation. + */ @Override public boolean cancel(boolean mayInterruptIfRunning) { return false;
null
train
val
"2018-01-24T19:42:13"
"2018-01-23T08:24:28Z"
laosijikaichele
val
netty/netty/7617_7627
netty/netty
netty/netty/7617
netty/netty/7627
[ "timestamp(timedelta=15.0, similarity=0.8980620280882211)" ]
b640797de17f1afef26fbae778fad13d6b93767d
d74d3217301f1ad308560a7532f935daca99356a
[ "@hank-whu it should be after 10 seconds maximum if there are no more references: https://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/internal/ObjectCleaner.java#L52\r\n\r\nAre you sure there are no more references hold ?", "@normanmaurer why isn't there a break in the loop if the thread is interrupted? wouldn't that indicate the application is shutting down?", "@johnou I think it should still cary on cleanup until there are no more references as otherwise we may leak direct memory etc. It should only exit once the `LIVE_SET` is empty imho. ", "@normanmaurer then how about a daemon thread? Allowing the JVM process to terminate in a timely manner.", "@johnou we decided against a daemon thread to make harder guarantees about cleanup. If it would be a deamon thread we may leak direct memory for example when someone hot-deploy stuff. \r\n\r\nAlso /cc @Scottmitch , as both of us had the discussion :)", "Yes we considered daemon but decided against it. Although I would expect most OSes we run on will clean up process resources after the process dies we can’t be sure of this. Since we allocate native resources outside the scope of the JVM the more conservative approach is to go non daemon. The mitigation factor was to have a timeout on the poll. This may cause issues if some of the jvm shutdown processing contains references to items registered in the cleaner but this seemed unlikely when the discussion took place.", "@normanmaurer \r\nshoud i wait 10 seconds after shutdown the EventLoopGroup ?\r\nit doesn't seem like a good way.\r\ncan add a \"shutdown(long mills)\" method to ObjectCleanerThread ?", "@hank-whu it may take up to 10 seconds... That said you can tune this with a system property:\r\n\r\nhttps://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/internal/ObjectCleaner.java#L36", "@normanmaurer it can actually stop the jvm from terminating, I'll post more details shortly. ", "Thx... \n\n> Am 25.01.2018 um 09:27 schrieb Johno Crawford <notifications@github.com>:\n> \n> @normanmaurer it can actually stop the jvm from terminating, I'll post more details shortly.\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Ensure all threads are closed, \"wait some time\" is the only way.\r\nI think this is not very good. \r\nI need a method to ensure all threads are closed.", "@normanmaurer I would expect something like this to exit gracefully without an explicit System.exit call.\r\n\r\n```java\r\npublic class Main {\r\n\r\n public static void main(String[] args) {\r\n ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();\r\n byteBuf.release();\r\n System.gc();\r\n System.runFinalization();\r\n // hangs because ObjectCleanerThread is not a daemon thread / LIVE_SET is not empty..\r\n }\r\n}\r\n```", "@johnou @hank-whu after reading more up on all of this I think you are right and @Scottmitch and myself were wrong .... This must be a deamon thread to ensure we will be able to shutdown in all cases. OpenJDK itself also uses a deamon thread and the GC threads are also deamon threads:\r\nhttps://github.com/dmlloyd/openjdk/blob/342a565a2da8abd69c4ab85e285bb5f03b48b2c9/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java#L117\r\n\r\nLet me come up with a PR", "@hank-whu @johnou https://github.com/netty/netty/pull/7627 PTAL", "@johnou - interesting example! interesting implication of having the main thread running the `main` method is objects referenced from here may not be GC'ed, or at least not detectable by the application.", "Fixed by https://github.com/netty/netty/pull/7627", "Hi @normanmaurer Any ETA for the next release? This issue is hurting us pretty badly :(", "Hopefully tomorrow, latest Friday. \n\n> On 31. Jan 2018, at 10:37, Stephane Landelle <notifications@github.com> wrote:\n> \n> Hi @normanmaurer <https://github.com/normanmaurer> Any ETA for the next release? This issue is hurting us pretty badly :(\n> \n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub <https://github.com/netty/netty/issues/7617#issuecomment-361876251>, or mute the thread <https://github.com/notifications/unsubscribe-auth/AAa0Qs7Ok-9ASZLNkWHepi64goFZNXf_ks5tQDRxgaJpZM4RrB4W>.\n> \n\n", "Wow, great, you rock!", "Hi, is this fix included in any 4.1.x release yet?", "@mcfongtw yep. since 4.1.21.", "Thanks. @fenik17 " ]
[ "never ending loop?", "Yeah this needs to be removed, done..", "@jaymode question... does this also need to be in a privileged block ?", "This is a good question. `Thread#setDaemon` does check permissions by calling `Thread#checkAccess`, but I think it is important to look at what happens there before wrapping in a doPrivileged block. In the default [SecurityManager](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkAccess(java.lang.Thread)), the access control is only enforced for system threads. In that case, I think this should not be wrapped since we are not modifying a system thread. In elasticsearch we use [SecureSM](https://github.com/elastic/securesm/blob/master/src/main/java/org/elasticsearch/SecureSM.java), which has a stricter policy but even then I don't think you'd want to elevate privileges here since modifying threads within your own threadgroup or one of its descendants is allowed.\r\n", "@jaymode thanks a lot for the answer and sorry for bothering you but after your last PR I was wondering if I am doing something stupid ;)" ]
"2018-01-25T13:00:28Z"
[ "defect" ]
ObjectCleanerThread not be closed
### Netty version 4.1.20.Final ### JVM version (e.g. `java -version`) 9.0.1 ### OS version (e.g. `uname -a`) Windows 10 Non-finished threads: Thread[DestroyJavaVM,5,main] Thread[ObjectCleanerThread,1,main] at java.base@9.0.1/java.lang.Object.wait(Native Method) at java.base@9.0.1/java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151) at app//io.netty.util.internal.ObjectCleaner$1.run(ObjectCleaner.java:52) at app//io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base@9.0.1/java.lang.Thread.run(Thread.java:844)
[ "common/src/main/java/io/netty/util/internal/ObjectCleaner.java" ]
[ "common/src/main/java/io/netty/util/internal/ObjectCleaner.java" ]
[ "common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java" ]
diff --git a/common/src/main/java/io/netty/util/internal/ObjectCleaner.java b/common/src/main/java/io/netty/util/internal/ObjectCleaner.java index 96d04439563..991f30d0dc0 100644 --- a/common/src/main/java/io/netty/util/internal/ObjectCleaner.java +++ b/common/src/main/java/io/netty/util/internal/ObjectCleaner.java @@ -16,8 +16,6 @@ package io.netty.util.internal; import io.netty.util.concurrent.FastThreadLocalThread; -import io.netty.util.internal.logging.InternalLogger; -import io.netty.util.internal.logging.InternalLoggerFactory; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; @@ -36,11 +34,13 @@ public final class ObjectCleaner { private static final int REFERENCE_QUEUE_POLL_TIMEOUT_MS = max(500, getInt("io.netty.util.internal.ObjectCleaner.refQueuePollTimeout", 10000)); + + // Package-private for testing + static final String CLEANER_THREAD_NAME = ObjectCleaner.class.getSimpleName() + "Thread"; // This will hold a reference to the AutomaticCleanerReference which will be removed once we called cleanup() private static final Set<AutomaticCleanerReference> LIVE_SET = new ConcurrentSet<AutomaticCleanerReference>(); private static final ReferenceQueue<Object> REFERENCE_QUEUE = new ReferenceQueue<Object>(); private static final AtomicBoolean CLEANER_RUNNING = new AtomicBoolean(false); - private static final String CLEANER_THREAD_NAME = ObjectCleaner.class.getSimpleName() + "Thread"; private static final Runnable CLEANER_TASK = new Runnable() { @Override public void run() { @@ -116,9 +116,9 @@ public Void run() { }); cleanupThread.setName(CLEANER_THREAD_NAME); - // This Thread is not a daemon as it will die once all references to the registered Objects will go away - // and its important to always invoke all cleanup tasks as these may free up direct memory etc. - cleanupThread.setDaemon(false); + // Mark this as a daemon thread to ensure that we the JVM can exit if this is the only thread that is + // running. + cleanupThread.setDaemon(true); cleanupThread.start(); } }
diff --git a/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java b/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java index 0db3e269456..7e755040211 100644 --- a/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java +++ b/common/src/test/java/io/netty/util/internal/ObjectCleanerTest.java @@ -23,6 +23,8 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public class ObjectCleanerTest { @@ -110,4 +112,26 @@ public void run() { Thread.sleep(100); } } + + @Test(timeout = 5000) + public void testCleanerThreadIsDaemon() throws Exception { + temporaryObject = new Object(); + ObjectCleaner.register(temporaryObject, new Runnable() { + @Override + public void run() { + // NOOP + } + }); + + Thread cleanerThread = null; + + for (Thread thread : Thread.getAllStackTraces().keySet()) { + if (thread.getName().equals(ObjectCleaner.CLEANER_THREAD_NAME)) { + cleanerThread = thread; + break; + } + } + assertNotNull(cleanerThread); + assertTrue(cleanerThread.isDaemon()); + } }
train
val
"2018-01-25T14:03:35"
"2018-01-24T10:25:46Z"
hank-whu
val
netty/netty/7638_7640
netty/netty
netty/netty/7638
netty/netty/7640
[ "timestamp(timedelta=23188.0, similarity=0.8445211806997002)" ]
bed74d8380c57302c771824548386d7f0cb79629
49d1db4113fb04b1d5001499d6c60fa9d3835aa4
[ "See the discussion in https://github.com/netty/netty/pull/7631 for more details including a possible solution.", "@bryce-anderson thanks a lot! I will fix it :)", "@bryce-anderson PTAL https://github.com/netty/netty/pull/7640", "Fixed" ]
[ "I also think the order of these two needs to be reversed, the following test fails:\r\n```java\r\n@Test\r\n public void channelClosedWhenClosePromiseCompletes() {\r\n LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream);\r\n Http2StreamChannel childChannel = (Http2StreamChannel) inboundHandler.channel();\r\n\r\n assertTrue(childChannel.isOpen());\r\n assertTrue(childChannel.isActive());\r\n\r\n final AtomicBoolean channelOpen = new AtomicBoolean(true);\r\n\r\n final ChannelPromise p = childChannel.newPromise();\r\n\r\n p.addListener(new ChannelFutureListener() {\r\n @Override\r\n public void operationComplete(ChannelFuture future) throws Exception {\r\n channelOpen.set(future.channel().isOpen());\r\n }\r\n });\r\n\r\n childChannel.close(p).syncUninterruptibly();\r\n\r\n assertFalse(channelOpen.get());\r\n }\r\n```\r\n\r\nReversing the order fixes the test above. I'm happy to file another bug if you prefer (perhaps that breaks something else I'm not aware of).", "+1 ... there was actually another issue too so I just submitted https://github.com/netty/netty/pull/7643 with a modified version of the unit test above." ]
"2018-01-26T19:38:34Z"
[ "defect" ]
The Http2MultiplexCodec StreamChannel will fire channelInactive without the channel.isOpen method reporting false
### Expected behavior When part of a HTTP/2 `StreamChannel` the `StreamChannel.isOpen()` method should report `false` within a call to a `ChannelInboundHandler`s `channelInactive` method. ### Actual behavior Within the `channelInactive` method, `ctx.channel().isOpen() == true` ### Minimal yet complete reproducer code (or URL to code) Within the `Http2MultiplexCodecTest: ```java @Test public void channelClosedWhenInactiveFired() { LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream); Http2StreamChannel childChannel = (Http2StreamChannel) inboundHandler.channel(); final AtomicBoolean channelWasOpen = new AtomicBoolean(false); childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channelWasOpen.set(ctx.channel().isOpen()); super.channelInactive(ctx); } }); childChannel.close().syncUninterruptibly(); assertFalse(channelWasOpen.get()); } ``` Result: java.lang.AssertionError io.netty.handler.codec.http2.Http2MultiplexCodecTest.channelClosedWhenInactiveFired(Http2MultiplexCodecTest.java:471) ### Netty version 4.1 ### JVM version (e.g. `java -version`) openjdk version "1.8.0_152" ### OS version (e.g. `uname -a`) Darwin
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java index aeeec3feb68..4972a044d59 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexCodec.java @@ -886,12 +886,14 @@ public void close(ChannelPromise promise) { } } + // The promise should be notified before we call fireChannelInactive(). + promise.setSuccess(); + closePromise.setSuccess(); + pipeline().fireChannelInactive(); if (isRegistered()) { deregister(unsafe().voidPromise()); } - promise.setSuccess(); - closePromise.setSuccess(); } finally { pendingClosePromise = null; }
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java index bec5cd964ee..4778729cd97 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecTest.java @@ -31,6 +31,7 @@ import io.netty.util.AttributeKey; import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; import org.junit.Before; @@ -420,6 +421,31 @@ public void writabilityAndFlowControl() { assertEquals("true,false", inboundHandler.writabilityStates()); } + @Test + public void channelClosedWhenInactiveFired() { + LastInboundHandler inboundHandler = streamActiveAndWriteHeaders(inboundStream); + Http2StreamChannel childChannel = (Http2StreamChannel) inboundHandler.channel(); + + final AtomicBoolean channelOpen = new AtomicBoolean(false); + final AtomicBoolean channelActive = new AtomicBoolean(false); + assertTrue(childChannel.isOpen()); + assertTrue(childChannel.isActive()); + + childChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + channelOpen.set(ctx.channel().isOpen()); + channelActive.set(ctx.channel().isActive()); + + super.channelInactive(ctx); + } + }); + + childChannel.close().syncUninterruptibly(); + assertFalse(channelOpen.get()); + assertFalse(channelActive.get()); + } + @Ignore("not supported anymore atm") @Test public void cancellingWritesBeforeFlush() {
train
val
"2018-01-26T17:33:49"
"2018-01-26T19:01:40Z"
bryce-anderson
val
netty/netty/7644_7645
netty/netty
netty/netty/7644
netty/netty/7645
[ "timestamp(timedelta=14.0, similarity=0.8972325862009453)" ]
614b9e0f25e81052ccd1357c7999d0e74a121663
6ff5c6faefaf47f43ecdf6d1c1051cd55e18141c
[ "Can you provide a pr for a fix ?\n\n> Am 27.01.2018 um 10:08 schrieb kashike <notifications@github.com>:\n> \n> The netty-all artifact doesn't have a Automatic-Module-Name defined in the manifest like the rest of the projects do, resulting in requires netty.all.\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "#7645" ]
[]
"2018-01-27T09:49:16Z"
[ "defect" ]
netty-all artifact missing automatic-module-name
The `netty-all` artifact doesn't have a `Automatic-Module-Name` defined in the manifest like the rest of the projects do, resulting in `requires netty.all`.
[ "README.md", "all/pom.xml" ]
[ "README.md", "all/pom.xml" ]
[]
diff --git a/README.md b/README.md index d45b41a917f..5c4c4b5afd8 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Netty can be used in modular JDK9 applications as a collection of automatic modu reverse-DNS style, and are derived from subproject names rather than root packages due to historical reasons. They are listed below: + * `io.netty.all` * `io.netty.buffer` * `io.netty.codec` * `io.netty.codec.dns` diff --git a/all/pom.xml b/all/pom.xml index b43869d6acc..f3e897d9a2b 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -664,6 +664,9 @@ <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> + <manifestEntries> + <Automatic-Module-Name>io.netty.all</Automatic-Module-Name> + </manifestEntries> <index>true</index> </archive> </configuration>
null
train
val
"2018-01-27T08:57:17"
"2018-01-27T09:08:36Z"
kashike
val
netty/netty/7588_7646
netty/netty
netty/netty/7588
netty/netty/7646
[ "timestamp(timedelta=21.0, similarity=0.8789671300627859)" ]
1c7125750b7f8205c263f6ec730357742b25d222
c7b776a1d224f84cb7f84afc42f8d7561905bcf6
[ "@ivankelly ups... this most be an oversight... you want to do a PR ?", "Can do, though it would probably be better for the person who originally pulled the harmony code to do so, so that you know what to bubble up. The original change was by @trustin (https://github.com/netty/netty/commit/681d46). From what I can tell it came from one of the last harmony releases, but I'm just guessing. ", "@ivankelly what do you mean by it doesn't cover the notice?", "From ASLv2 4d\r\n\r\n> If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. \r\n\r\nApache harmony has a NOTICE file (as all ASF projects have), and as such this must be included as a readable copy in the derivative work (netty).", "@ivankelly Does this mean this issue will be resolved once we add Harmony's NOTICE file somewhere in our repository? Do we also need to include that file in JAR files?", "@trustin I don't think you need, nor should, pull in the whole notice file. From ASLv2 4d, \"excluding those notices that do not pertain to any part of the Derivative Works\". The parts you pulled into AsciiString seem to be only from java.lang.String, which is code which IBM contributed to harmony, but they assigned copyright to ASF when they did so. I had to dig into this when getting our own NOTICE up to scratch, which is when I found this issue.", "@trustin but this also depends on where you pulled the harmony code from. Do you remember?", "@ivankelly I think I pulled it in from the official repository. It was a very long time ago, though. Looking into the NOTICE file at: http://svn.apache.org/viewvc/harmony/enhanced/java/trunk/NOTICE?view=markup\r\n\r\n> The parts you pulled into AsciiString seem to be only from java.lang.String, which is code which IBM contributed to harmony,\r\n\r\nYes, that's correct.\r\n\r\n> but they assigned copyright to ASF when they did so. I had to dig into this when getting our own NOTICE up to scratch, which is when I found this issue.\r\n\r\nI'm not really sure how our 'partial NOTICE file' has to look like, then. What about this:\r\n\r\n```\r\nApache Harmony\r\n\r\nCopyright 2006, 2010 The Apache Software Foundation.\r\n\r\nThis product includes software developed at\r\nThe Apache Software Foundation (http://www.apache.org/).\r\n\r\n(C) Copyright 1997,2004 International Business Machines Corporation.\r\nAll rights reserved.\r\n\r\n(C) Copyright IBM Corp. 2003. \r\n```\r\n\r\n.. or should I remove the IBM part since IBM assigned copyright to the ASF when they contribute? If IBM part can be removed, this leaves merely the first six lines which seem redundant to me. Do I still have to keep this file?\r\n", "@trustin AFAIK, regarding the code pulled in, the IBM lines are not needed. \r\n\r\nwhy do you say that the first 6 lines are redundant? It's informing the end user that the project contains code which is copyrighted to the ASF", "Note that AsciiString has been reworked (IIUC it was removed and brought back) since its original introduction in Netty. @trustin - can you verify if the attribution is still necessary?", "@Scottmitch possibly, though the latest asciistring code contains some methods which are strikingly similar to harmony, so i think the need for attribution still stands.", "> why do you say that the first 6 lines are redundant?\r\n\r\nBecause we mentioned that in our NOTICE.txt file although it's not verbatim. I can add it anyway, though. Will send a PR this week.", "Are you sure? I don't see it.", "@ivankelly https://github.com/netty/netty/blob/4.1/NOTICE.txt#L61 It's just an implicit mention, so let me just make it clear by adding the file.", "@ivankelly - out of curiosity can you point out which methods?", "@trustin ah, ya, i think that's a little too implicit :)", "@Scottmitch \r\none is \"int indexOf(CharSequence subString, int start)\"\r\n\r\nFrom apache-harmony-6.0-src-r991881 String.java:\r\n```\r\n public int indexOf(String subString, int start) {\r\n if (start < 0) {\r\n start = 0;\r\n }\r\n int subCount = subString.count;\r\n if (subCount > 0) {\r\n if (subCount + start > count) {\r\n return -1;\r\n }\r\n char[] target = subString.value;\r\n int subOffset = subString.offset;\r\n char firstChar = target[subOffset];\r\n int end = subOffset + subCount;\r\n while (true) {\r\n int i = indexOf(firstChar, start);\r\n if (i == -1 || subCount + i > count) {\r\n return -1; // handles subCount > count || start >= count \r\n }\r\n int o1 = offset + i, o2 = subOffset;\r\n while (++o2 < end && value[++o1] == target[o2]) {\r\n // Intentionally empty \r\n }\r\n if (o2 == end) {\r\n return i;\r\n }\r\n start = i + 1;\r\n }\r\n }\r\n return start < count ? start : count;\r\n }\r\n```\r\n\r\nFrom AsciiString.java:\r\n```\r\n public int indexOf(CharSequence subString, int start) {\r\n if (start < 0) {\r\n start = 0;\r\n }\r\n\r\n final byte[] value = this.value;\r\n final int thisLen = value.length;\r\n\r\n int subCount = subString.length();\r\n if (subCount <= 0) {\r\n return start < thisLen ? start : thisLen;\r\n }\r\n if (subCount > thisLen - start) {\r\n return -1;\r\n }\r\n\r\n char firstChar = subString.charAt(0);\r\n for (;;) {\r\n int i = indexOf(firstChar, start);\r\n if (i == -1 || subCount + i > thisLen) {\r\n return -1; // handles subCount > count || start >= count \r\n }\r\n int o1 = i, o2 = 0;\r\n while (++o2 < subCount && (value[++o1] & 0xFF) == subString.charAt(o2)) {\r\n // Intentionally empty \r\n }\r\n if (o2 == subCount) {\r\n return i;\r\n }\r\n start = i + 1;\r\n }\r\n }\r\n```\r\n\r\nThe comments are a giveaway", "tbh it looks like the code was rewritten (with flow changes and improvements, not just changing variable names, the produced bytecode varies greatly) the comments could easily be rewritten too if that's a problem.", "@johnou It's still a derivative work.", "we should make what ever attribution to Harmony (despite the rework) is required in the NOTICE file.\r\n\r\n@trustin - can you take care?", "👍\n\n> Am 18.01.2018 um 19:35 schrieb Scott Mitchell <notifications@github.com>:\n> \n> we should make what ever attribution to Harmony (despite the rework) is required in the NOTICE file.\n> \n> @trustin - can you take care?\n> \n> —\n> You are receiving this because you commented.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "@trustin poke" ]
[ "Would be more accurate to put it under a NOTICE: header, but this is fine too.", "Sure. Will update.", "yeah but it's still in the license directory.", "Yeah, but I'm not sure I want to add another top-level directory just for this. Perhaps when we have more of these?" ]
"2018-01-29T01:15:44Z"
[ "cleanup" ]
Netty NOTICE doesn't cover Apache Harmony's notice
... which is required by the ASLv2. https://www.apache.org/licenses/LICENSE-2.0 (section 4d.)
[ "NOTICE.txt" ]
[ "NOTICE.txt", "license/NOTICE.harmony.txt" ]
[]
diff --git a/NOTICE.txt b/NOTICE.txt index 26b5374398b..f973663670b 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -61,6 +61,8 @@ facade for Java, which can be obtained at: This product contains a modified portion of 'Apache Harmony', an open source Java SE, which can be obtained at: + * NOTICE: + * license/NOTICE.harmony.txt * LICENSE: * license/LICENSE.harmony.txt (Apache License 2.0) * HOMEPAGE: diff --git a/license/NOTICE.harmony.txt b/license/NOTICE.harmony.txt new file mode 100644 index 00000000000..036ba0d4bb2 --- /dev/null +++ b/license/NOTICE.harmony.txt @@ -0,0 +1,6 @@ +Apache Harmony + +Copyright 2006, 2010 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/).
null
train
val
"2018-01-27T20:31:16"
"2018-01-16T13:02:38Z"
ivankelly
val
netty/netty/7660_7661
netty/netty
netty/netty/7660
netty/netty/7661
[ "timestamp(timedelta=12.0, similarity=0.8564761240650354)" ]
69582c0b6c190e57e8365c97aa819ac5e965a5bd
529b2c11eef30d7c7e5191852afcf1b6b2a77712
[ "@teaey we will need some more details etc to be able to fix this. Can you give some more or share some code ?", "@normanmaurer Please see : https://github.com/teaey/netty/commit/1cf24675c9e90d29d799e6184a9da13a2984a0f9\r\n\r\nCan I make a PR for this Issue.", "@teaey looks useful... yeah please open a PR and I will comment there. Thanks!", "@normanmaurer Done", "@normanmaurer ,I suggested he to make a PR, he is sitting beside me now.", "@hepin1989 awesome :) Thanks @teaey", "@teaey I enjoy this enhancement, good job. ", "This one is a little less obvious and there are two components. For starters, if you’re compressing data that are smaller than the MTU size of a TCP packet, you’re wasting CPU time. 1500 bytes is the MTU size for the internet since that is the largest size allowed at the network layer. If you take data package that is 1300 bytes and compress it to 800 bytes, it’s still transmitted in that same 1500 byte packet regardless, so you’ve gained nothing. That being the case, you should restrict the gzip compression to data bytes with a size greater than a single packet, 1400 bytes (1.4KB) is a safe value.\r\n\r\njust set this threshold with 1400+ as default value. avoid to CPU cost.", "@pli2014 I think we should keep 0 as default value to not change behaviour. ", "@normanmaurer using this default value in constructor method or comment this explanation within code. I propose this for other users.", "Maybe we could introduce a static constant field as a suggested value?", "@hepin1989 @pli2014 I think we should not suggest anything as what makes sense highly depends... for example even if you use smaller buffers as the mtu size it may make sense if you do a gathering write.", "Let users decide how to use it.", "Merged..." ]
[ "nit: can you move this to the other final variables.", "add whitespace after `,`", "We need to keep the existing constructor to not break the API. Please just create an extra constructor and delegate to it.", "Explain that `<= 0` will disable this.", "add space after `if`", "\r\n@teaey please reword to:\r\n\r\nReturns {@code true} if the compression should be used. May be override to change default behaviour", "rename to `useCompression(...)`", "nit: s/If/if/", "change to: `{@code 0}` will enable compression for all responses.", "@teaey sorry one last nit... I think this should be the first thing to check as we not need to even compare headers if it is false. Please move it before the header check", "This looks like it only works properly for a FullHttpResponse. If a HttpResponse was sent separately than a HttpContent(s), then this won't compress. Is that intended?", "sizeThreshold? payloadSizeThreshold? compressThreshold just makes me question what it means (e.g., threshold of compression ratio?).", "Why is this protected?", "I'd feel better with throwing if negative.", "Hi @ejona86. \r\n\r\nUsers can implement the subclass to overwrite the useCompression method, which may access the compressThreshold field.", "Yes, throwing is in line with other fields.\r\n@normanmaurer What's your opinion?", "👍 \r\nWhat about contentSizeThreshold?", "This is in line with the original class.", "SGTM", "Oh, I see, although the extending class passed it in (so it could save it itself) and I can't come up with anything it would do with it.\r\n\r\nSpeaking of which, why is `useCompression` protected? If I'm extending this class can't I override `beginEncode` with basically same amount of difficulty? It also wasn't necessary before; why is it needed now with threshold?" ]
"2018-01-31T08:25:32Z"
[ "improvement", "feature" ]
io.netty.handler.codec.http.HttpContentCompressor need compress threshold
### Expected behavior the response body is compressed, when the response body exceeds the threshold ### Actual behavior no threshold can be set ### Steps to reproduce - ### Minimal yet complete reproducer code (or URL to code) - ### Netty version 4.1.16.Final ### JVM version (e.g. `java -version`) java 1.8 ### OS version (e.g. `uname -a`) -
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java index fcf22e011ad..e80469f26e4 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentCompressor.java @@ -32,6 +32,7 @@ public class HttpContentCompressor extends HttpContentEncoder { private final int compressionLevel; private final int windowBits; private final int memLevel; + private final int contentSizeThreshold; private ChannelHandlerContext ctx; /** @@ -52,7 +53,7 @@ public HttpContentCompressor() { * compression level is {@code 6}. */ public HttpContentCompressor(int compressionLevel) { - this(compressionLevel, 15, 8); + this(compressionLevel, 15, 8, 0); } /** @@ -75,6 +76,33 @@ public HttpContentCompressor(int compressionLevel) { * at the expense of memory usage. The default value is {@code 8} */ public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel) { + this(compressionLevel, windowBits, memLevel, 0); + } + + /** + * Creates a new handler with the specified compression level, window size, + * and memory level.. + * + * @param compressionLevel + * {@code 1} yields the fastest compression and {@code 9} yields the + * best compression. {@code 0} means no compression. The default + * compression level is {@code 6}. + * @param windowBits + * The base two logarithm of the size of the history buffer. The + * value should be in the range {@code 9} to {@code 15} inclusive. + * Larger values result in better compression at the expense of + * memory usage. The default value is {@code 15}. + * @param memLevel + * How much memory should be allocated for the internal compression + * state. {@code 1} uses minimum memory and {@code 9} uses maximum + * memory. Larger values result in better and faster compression + * at the expense of memory usage. The default value is {@code 8} + * @param contentSizeThreshold + * The response body is compressed when the size of the response + * body exceeds the threshold. The value should be a non negative + * number. {@code 0} will enable compression for all responses. + */ + public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel, int contentSizeThreshold) { if (compressionLevel < 0 || compressionLevel > 9) { throw new IllegalArgumentException( "compressionLevel: " + compressionLevel + @@ -88,9 +116,14 @@ public HttpContentCompressor(int compressionLevel, int windowBits, int memLevel) throw new IllegalArgumentException( "memLevel: " + memLevel + " (expected: 1-9)"); } + if (contentSizeThreshold < 0) { + throw new IllegalArgumentException( + "contentSizeThreshold: " + contentSizeThreshold + " (expected: non negative number)"); + } this.compressionLevel = compressionLevel; this.windowBits = windowBits; this.memLevel = memLevel; + this.contentSizeThreshold = contentSizeThreshold; } @Override @@ -100,6 +133,13 @@ public void handlerAdded(ChannelHandlerContext ctx) throws Exception { @Override protected Result beginEncode(HttpResponse headers, String acceptEncoding) throws Exception { + if (this.contentSizeThreshold > 0) { + if (headers instanceof HttpContent && + ((HttpContent) headers).content().readableBytes() < contentSizeThreshold) { + return null; + } + } + String contentEncoding = headers.headers().get(HttpHeaderNames.CONTENT_ENCODING); if (contentEncoding != null) { // Content-Encoding was set, either as something specific or as the IDENTITY encoding
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java index c6ff3bd6bc0..6ab2ab88c62 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentCompressorTest.java @@ -29,11 +29,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; public class HttpContentCompressorTest { @@ -454,6 +450,52 @@ public void testCustomEncoding() throws Exception { assertTrue(ch.finishAndReleaseAll()); } + @Test + public void testCompressThresholdAllCompress() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor()); + assertTrue(ch.writeInbound(newRequest())); + + FullHttpResponse res1023 = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(new byte[1023])); + assertTrue(ch.writeOutbound(res1023)); + DefaultHttpResponse response1023 = ch.readOutbound(); + assertThat(response1023.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("gzip")); + ch.releaseOutbound(); + + assertTrue(ch.writeInbound(newRequest())); + FullHttpResponse res1024 = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(new byte[1024])); + assertTrue(ch.writeOutbound(res1024)); + DefaultHttpResponse response1024 = ch.readOutbound(); + assertThat(response1024.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("gzip")); + assertTrue(ch.finishAndReleaseAll()); + } + + @Test + public void testCompressThresholdNotCompress() throws Exception { + EmbeddedChannel ch = new EmbeddedChannel(new HttpContentCompressor(6, 15, 8, 1024)); + assertTrue(ch.writeInbound(newRequest())); + + FullHttpResponse res1023 = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(new byte[1023])); + assertTrue(ch.writeOutbound(res1023)); + DefaultHttpResponse response1023 = ch.readOutbound(); + assertFalse(response1023.headers().contains(HttpHeaderNames.CONTENT_ENCODING)); + ch.releaseOutbound(); + + assertTrue(ch.writeInbound(newRequest())); + FullHttpResponse res1024 = new DefaultFullHttpResponse( + HttpVersion.HTTP_1_1, HttpResponseStatus.OK, + Unpooled.wrappedBuffer(new byte[1024])); + assertTrue(ch.writeOutbound(res1024)); + DefaultHttpResponse response1024 = ch.readOutbound(); + assertThat(response1024.headers().get(HttpHeaderNames.CONTENT_ENCODING), is("gzip")); + assertTrue(ch.finishAndReleaseAll()); + } + private static FullHttpRequest newRequest() { FullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); req.headers().set(HttpHeaderNames.ACCEPT_ENCODING, "gzip");
val
val
"2018-02-21T13:52:33"
"2018-01-31T07:17:08Z"
teaey
val
netty/netty/7662_7663
netty/netty
netty/netty/7662
netty/netty/7663
[ "timestamp(timedelta=3.0, similarity=0.9536617993150428)" ]
e00f24961adbd1ed0e2189cf5ca9dc16632faa7c
1a2d48ea1255bc562f7732c8a6f4ad1d84e699d1
[ "This would be very nice to have.\r\nI've been using:\r\n`if (pipeline.names.contains(\"someHandler\")`\r\n", "Fixed by https://github.com/netty/netty/pull/7663" ]
[ "@doom369 I think this is not safe as in the meantime it could have been removed from another thread which would have this method throw a `NoSuchElementException`", "@normanmaurer I don't see any place where NoSuchElementException could be thrown in above code.", "ah never mind... this should work... " ]
"2018-01-31T12:10:44Z"
[]
Proposal: add removeIfExists() method to ChannelPipeline
In some cases, I have to remove the handler from the pipeline that may exist or may not. Current Netty `remove()` implementation always throws `NoSuchElementException` that requires construction like this: ``` try { pipeline.remove(LetsEncryptHandler.class); } catch (NoSuchElementException e) { } ``` this could be simplified with: `pipeline.removeIfExists(LetsEncryptHandler.class);` WDYT?
[ "transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java" ]
[ "transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java" ]
[ "transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java index e9d92a13970..0d3307a5351 100644 --- a/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java +++ b/transport/src/main/java/io/netty/channel/DefaultChannelPipeline.java @@ -457,6 +457,26 @@ public final <T extends ChannelHandler> T remove(Class<T> handlerType) { return (T) remove(getContextOrDie(handlerType)).handler(); } + public final <T extends ChannelHandler> T removeIfExists(String name) { + return removeIfExists(context(name)); + } + + public final <T extends ChannelHandler> T removeIfExists(Class<T> handlerType) { + return removeIfExists(context(handlerType)); + } + + public final <T extends ChannelHandler> T removeIfExists(ChannelHandler handler) { + return removeIfExists(context(handler)); + } + + @SuppressWarnings("unchecked") + private <T extends ChannelHandler> T removeIfExists(ChannelHandlerContext ctx) { + if (ctx == null) { + return null; + } + return (T) remove((AbstractChannelHandlerContext) ctx).handler(); + } + private AbstractChannelHandlerContext remove(final AbstractChannelHandlerContext ctx) { assert ctx != head && ctx != tail;
diff --git a/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java b/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java index 6071649b340..7cd51b2999f 100644 --- a/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java +++ b/transport/src/test/java/io/netty/channel/DefaultChannelPipelineTest.java @@ -48,6 +48,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.NoSuchElementException; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; @@ -184,6 +185,52 @@ public void testRemoveChannelHandler() { assertNull(pipeline.get("handler3")); } + @Test + public void testRemoveIfExists() { + DefaultChannelPipeline pipeline = new DefaultChannelPipeline(new LocalChannel()); + + ChannelHandler handler1 = newHandler(); + ChannelHandler handler2 = newHandler(); + ChannelHandler handler3 = newHandler(); + + pipeline.addLast("handler1", handler1); + pipeline.addLast("handler2", handler2); + pipeline.addLast("handler3", handler3); + + assertNotNull(pipeline.removeIfExists(handler1)); + assertNull(pipeline.get("handler1")); + + assertNotNull(pipeline.removeIfExists("handler2")); + assertNull(pipeline.get("handler2")); + + assertNotNull(pipeline.removeIfExists(TestHandler.class)); + assertNull(pipeline.get("handler3")); + } + + @Test + public void testRemoveIfExistsDoesNotThrowException() { + DefaultChannelPipeline pipeline = new DefaultChannelPipeline(new LocalChannel()); + + ChannelHandler handler1 = newHandler(); + ChannelHandler handler2 = newHandler(); + pipeline.addLast("handler1", handler1); + + assertNull(pipeline.removeIfExists("handlerXXX")); + assertNull(pipeline.removeIfExists(handler2)); + assertNull(pipeline.removeIfExists(ChannelOutboundHandlerAdapter.class)); + assertNotNull(pipeline.get("handler1")); + } + + @Test(expected = NoSuchElementException.class) + public void testRemoveThrowNoSuchElementException() { + DefaultChannelPipeline pipeline = new DefaultChannelPipeline(new LocalChannel()); + + ChannelHandler handler1 = newHandler(); + pipeline.addLast("handler1", handler1); + + pipeline.remove("handlerXXX"); + } + @Test public void testReplaceChannelHandler() { ChannelPipeline pipeline = new LocalChannel().pipeline();
train
val
"2018-02-16T07:57:43"
"2018-01-31T11:04:27Z"
doom369
val
netty/netty/7673_7677
netty/netty
netty/netty/7673
netty/netty/7677
[ "timestamp(timedelta=0.0, similarity=0.9562389561464967)" ]
fe5c69bdd9d65ddd604a03bfc71081b5bc2ad40a
3f3d309a28f66f463bf7c6ade14e7908019b8aae
[ "@slandelle are you sure this was introduced in 4.1.20 ?", "@normanmaurer This renaming was introduced in 449befa0034e2cf77b3033f62d4f2153cef5a1d7 which is tagged as 4.1.20. ", "My bad, I didn't get what those tags meant in the GH interface. I guess it's from 4.1.13.", "I guess this went unnoticed as `SslUtils#DEFAULT_CIPHER_SUITES` only contains names prefixed with TLS.", "cc @Scottmitch @rkapsi", "http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites\r\n> The names mentioned in the TLS RFCs prefixed with TLS_ are functionally equivalent to the JSSE cipher suites prefixed with SSL_.\r\n\r\nArg. I guess the names aren't quite interchangeable. See https://github.com/netty/netty/pull/7677" ]
[ "Shouldn't you fall back to adding the original name here?", "the original name has already been added above on line 97, and is known to be supported because it's returned by `engine.getSupportedCipherSuites()`.", "Oh right" ]
"2018-02-01T16:41:52Z"
[ "defect" ]
JdkSslContext produces invalid supported ciphers
### Expected behavior JdkSslContext should produce valid ciphers that are actually supported by the platform. Typically, it should be possible to use them in a custom `CipherSuiteFilter` to configure a `SSLEngine`. ### Actual behavior Netty 4.1.13.Final introduced a workaround for IBM certs naming scheme. This workaround is based on IBM's statement: > According to IBM's documentation [2] the "SSL_" prefix is "interchangeable" with the "TLS_" prefix. This statement is wrong and transformed names cause `SSLEngine#setEnabledCipherSuites` to crash. On my machine, the following ciphers get transformed with the `SSL` prefix being replaced with `TLS` and cause SSLEngine to crash: * SSL_DH_anon_WITH_DES_CBC_SHA * SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA * SSL_DH_anon_WITH_3DES_EDE_CBC_SHA * SSL_DHE_RSA_WITH_DES_CBC_SHA * SSL_RSA_WITH_DES_CBC_SHA * SSL_DHE_DSS_WITH_DES_CBC_SHA * SSL_RSA_WITH_NULL_SHA * SSL_RSA_WITH_3DES_EDE_CBC_SHA * SSL_RSA_WITH_NULL_MD5 * SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA ### Steps to reproduce See reproducer below. ### Minimal yet complete reproducer code (or URL to code) ```java SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLEngine sslEngine = sslcontext.createSSLEngine(); // works sslEngine.setEnabledCipherSuites(new String[] {"SSL_DH_anon_WITH_DES_CBC_SHA"}); // crashes with IllegalArgumentException: Unsupported ciphersuite TLS_DH_anon_WITH_DES_CBC_SHA sslEngine.setEnabledCipherSuites(new String[] {"TLS_DH_anon_WITH_DES_CBC_SHA"}); ``` ### Netty version Tested on 4.1.20.Final ### JVM version (e.g. `java -version`) Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode) ### OS version (e.g. `uname -a`) Not relevant
[ "handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslContextTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java b/handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java index e027036146a..41fd9c6f6a8 100644 --- a/handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java +++ b/handler/src/main/java/io/netty/handler/ssl/JdkSslContext.java @@ -105,7 +105,13 @@ public class JdkSslContext extends SslContext { //[3] https://www.ibm.com/developerworks/community/forums/html/topic?id=9b5a56a9-fa46-4031-b33b-df91e28d77c2 //[4] https://www.ibm.com/developerworks/rfe/execute?use_case=viewRfe&CR_ID=71770 if (supportedCipher.startsWith("SSL_")) { - SUPPORTED_CIPHERS.add("TLS_" + supportedCipher.substring("SSL_".length())); + final String tlsPrefixedCipherName = "TLS_" + supportedCipher.substring("SSL_".length()); + try { + engine.setEnabledCipherSuites(new String[]{tlsPrefixedCipherName}); + SUPPORTED_CIPHERS.add(tlsPrefixedCipherName); + } catch (IllegalArgumentException ignored) { + // The cipher is not supported ... move on to the next cipher. + } } } List<String> ciphers = new ArrayList<String>();
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java b/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java index 76526a5b259..1c0032885ac 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java @@ -18,12 +18,20 @@ import org.junit.Assert; import org.junit.Test; -import javax.net.ssl.SSLException; import java.io.File; import java.io.IOException; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assume.assumeNotNull; + public abstract class SslContextTest { @Test(expected = IOException.class) @@ -85,5 +93,26 @@ public void testSslServerWithUnencryptedPrivateKeyEmptyPass() throws SSLExceptio newServerContext(crtFile, keyFile, ""); } + @Test + public void testSupportedCiphers() throws KeyManagementException, NoSuchAlgorithmException, SSLException { + SSLContext jdkSslContext = SSLContext.getInstance("TLS"); + jdkSslContext.init(null, null, null); + SSLEngine sslEngine = jdkSslContext.createSSLEngine(); + + String unsupportedCipher = "TLS_DH_anon_WITH_DES_CBC_SHA"; + IllegalArgumentException exception = null; + try { + sslEngine.setEnabledCipherSuites(new String[] {unsupportedCipher}); + } catch (IllegalArgumentException e) { + exception = e; + } + assumeNotNull(exception); + File keyFile = new File(getClass().getResource("test_unencrypted.pem").getFile()); + File crtFile = new File(getClass().getResource("test.crt").getFile()); + + SslContext sslContext = newServerContext(crtFile, keyFile, null); + assertFalse(sslContext.cipherSuites().contains(unsupportedCipher)); + } + protected abstract SslContext newServerContext(File crtFile, File keyFile, String pass) throws SSLException; }
test
val
"2018-02-01T09:31:07"
"2018-02-01T10:54:23Z"
slandelle
val
netty/netty/7655_7691
netty/netty
netty/netty/7655
netty/netty/7691
[ "timestamp(timedelta=20.0, similarity=0.84721031543362)" ]
1e70d3092d547b1d19f9bf3a4da231701d19de6a
3024b1478203f6772f1f4552ca9918a7f3c4c17d
[ "Would you be interested in a PR that would introduce a System prop that would disable filtering?", "So actually, a way better way to implement this would be to have a `CipherSuiteFilter` that, on contrary to `IdentityCipherSuiteFilter`, falls back to `supportedCiphers` instead of `defaultCiphers` when `ciphers` is null (ie when user didn't explicitly pass a set of ciphers).\r\nIt would be more convenient than having users duplicate Netty code for computing `supportedCiphers` for both JDK and OpenSSL providers and explicitly pass them.\r\n\r\n@normanmaurer Does it make sense? Should I do a PR for this? Or am I wrong?", "Yes this should be achievable via a `CipherSuiteFilter`. I don't think we should change the current behavior of `IdentityCipherSuiteFilter`, but what about creation of a new filter with this new behavior?", "Yes, that's exactly what I meant. Sorry if I wasn't clear...", "Sure. It doesn't have to be part of Netty, but if you think it is useful for others then feel free to submit a PR.", "Will do later tonight ", "Fixed by https://github.com/netty/netty/pull/7691" ]
[]
"2018-02-05T11:55:16Z"
[ "feature" ]
Provide a way to disable cipher suites filtering
### Expected behavior There should be a way to have client side `SslContext` work against any website, regardless of security. ### Actual behavior Supported ciphers are filtered against a hard coded whitelist (`SslUtils#DEFAULT_CIPHER_SUITES`). I wonder if the whitelist way is a good thing. Wouldn't it filter out modern ciphers that would be introduced in JDK updates? Properly maintaining this blacklist would require Netty core devs to frequently update it. Wouldn't a blacklist work better: ban ciphers that are known as unsecure? Then, my core issue is that there's no way to disable this security. On the client side, sometimes security is not the top most priority and users just want things to work, all the more as they do work with all the other user agents around (browsers, curl, Apache HttpComponents). Typical examples are load tests and web crawlers. ### Steps to reproduce For example, it's not possible to connect to "https://www.gretalr.com" with a `JdkSslHandler` while it's possible with any other user agent I know of (reported against AHC as https://github.com/AsyncHttpClient/async-http-client/issues/1510). ### Minimal yet complete reproducer code (or URL to code) ```java EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); final SslContext sslContext = SslContextBuilder.forClient().build(); final CountDownLatch latch = new CountDownLatch(1); Bootstrap b = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel nioSocketChannel) { SSLEngine sslEngine = sslContext.newEngine(nioSocketChannel.alloc(), "www.gretalr.com", 443); SslHandler sslHandler = new SslHandler(sslEngine); sslHandler.handshakeFuture().addListener(whenHandshaked -> { if (whenHandshaked.isSuccess()) { System.out.println("All good"); } else { whenHandshaked.cause().printStackTrace(); } latch.countDown(); }); nioSocketChannel.pipeline().addLast(sslHandler); } }); Channel channel = b.connect("www.gretalr.com", 443).sync().channel(); latch.await(); channel.close(); eventLoopGroup.shutdownGracefully(); ``` Note: I can connect fine if I create the SSLEngine from a `javax.net.ssl.SSLContext` instead. ### Netty version 4.1.20.Final ### JVM version (e.g. `java -version`) 1.8.0_152 ### OS version (e.g. `uname -a`) not relevant
[ "handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/IdentityCipherSuiteFilterTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java b/handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java index c9ebfb0da26..cfd5bb7b2a9 100644 --- a/handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java +++ b/handler/src/main/java/io/netty/handler/ssl/IdentityCipherSuiteFilter.java @@ -23,15 +23,31 @@ * This class will not do any filtering of ciphers suites. */ public final class IdentityCipherSuiteFilter implements CipherSuiteFilter { - public static final IdentityCipherSuiteFilter INSTANCE = new IdentityCipherSuiteFilter(); - private IdentityCipherSuiteFilter() { } + /** + * Defaults to default ciphers when provided ciphers are null + */ + public static final IdentityCipherSuiteFilter INSTANCE = new IdentityCipherSuiteFilter(true); + + /** + * Defaults to supported ciphers when provided ciphers are null + */ + public static final IdentityCipherSuiteFilter INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS = + new IdentityCipherSuiteFilter(false); + + private final boolean defaultToDefaultCiphers; + + private IdentityCipherSuiteFilter(boolean defaultToDefaultCiphers) { + this.defaultToDefaultCiphers = defaultToDefaultCiphers; + } @Override public String[] filterCipherSuites(Iterable<String> ciphers, List<String> defaultCiphers, Set<String> supportedCiphers) { if (ciphers == null) { - return defaultCiphers.toArray(new String[defaultCiphers.size()]); + return defaultToDefaultCiphers ? + defaultCiphers.toArray(new String[defaultCiphers.size()]) : + supportedCiphers.toArray(new String[supportedCiphers.size()]); } else { List<String> newCiphers = new ArrayList<String>(supportedCiphers.size()); for (String c : ciphers) { @@ -43,5 +59,4 @@ public String[] filterCipherSuites(Iterable<String> ciphers, List<String> defaul return newCiphers.toArray(new String[newCiphers.size()]); } } - }
diff --git a/handler/src/test/java/io/netty/handler/ssl/IdentityCipherSuiteFilterTest.java b/handler/src/test/java/io/netty/handler/ssl/IdentityCipherSuiteFilterTest.java new file mode 100644 index 00000000000..fd2dad8dc83 --- /dev/null +++ b/handler/src/test/java/io/netty/handler/ssl/IdentityCipherSuiteFilterTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.ssl; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertArrayEquals; + +public class IdentityCipherSuiteFilterTest { + + @Test + public void regularInstanceDefaultsToDefaultCiphers() { + List<String> defaultCiphers = Arrays.asList("FOO", "BAR"); + Set<String> supportedCiphers = new HashSet<String>(Arrays.asList("BAZ", "QIX")); + String[] filtered = IdentityCipherSuiteFilter.INSTANCE + .filterCipherSuites(null, defaultCiphers, supportedCiphers); + assertArrayEquals(defaultCiphers.toArray(), filtered); + } + + @Test + public void alternativeInstanceDefaultsToSupportedCiphers() { + List<String> defaultCiphers = Arrays.asList("FOO", "BAR"); + Set<String> supportedCiphers = new HashSet<String>(Arrays.asList("BAZ", "QIX")); + String[] filtered = IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS + .filterCipherSuites(null, defaultCiphers, supportedCiphers); + assertArrayEquals(supportedCiphers.toArray(), filtered); + } +}
val
val
"2018-02-05T09:05:51"
"2018-01-30T12:37:56Z"
slandelle
val
netty/netty/7724_7727
netty/netty
netty/netty/7724
netty/netty/7727
[ "timestamp(timedelta=151.0, similarity=0.953443813712184)" ]
dc3036a20201ef031f231e12cfe30d622779a0a1
268b901844c620337bc11ae82e99163a1781b96c
[ "@jianglai thanks I will check.", "@jianglai should be fixed by https://github.com/netty/netty/pull/7727.", "Thanks for the quick turnaround!", "@jianglai no problem... would be nice if you can verify the fix", "fixed by #7727", "Confirmed that with 4.1.22.Final-SNAPSHOT, the demo code works as intended.\r\n\r\nThanks!", "@jianglai thanks a lot !" ]
[]
"2018-02-16T08:06:33Z"
[ "defect" ]
SSL connection not closed properly after handshake failure in v4.1.21
### Expected behavior When SSL handshake fails, the connection is closed. ### Actual behavior Even though the SSL engine is closed, the connection itself is not closed. ### Steps to reproduce See below. ### Minimal yet complete reproducer code (or URL to code) Run the demo code [here](https://github.com/jianglai/netty-bug/blob/master/src/main/java/test/Main.java). The program hangs and "Channel closed." is never printed to stdout. If you change the Netty version in the pom.xml file to 4.1.17, the channel is closed as expected. ### Netty version 4.1.21 ### JVM version (e.g. `java -version`) openjdk version "1.8.0_112-google-v7" OpenJDK Runtime Environment (build 1.8.0_112-google-v7-181886826-181741640) OpenJDK 64-Bit Server VM (build 25.112-b01, mixed mode) ### OS version (e.g. `uname -a`) Linux 4.9.0-5-amd64 SMP Debian 4.9.65-3+deb9u2 (2018-01-04) x86_64 GNU/Linux I think this is a regression introduced by https://github.com/netty/netty/commit/978a46cc0a5242702f248842f6feb97b8fbe0123. More specifically, [`handshakePromise.tryFailure`](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/SslHandler.java#L1183) is called within the `try` clause, and the promise is set to failure. Later in the `finally` clause, [`setHandshakeFailure`](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/SslHandler.java#L1529) calls [`notifyHandshakeFailure`](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/SslHandler.java#L1542]), which is no longer calling [`SslUtils.notifyHandshakeFailure`](https://github.com/netty/netty/blob/4.1/handler/src/main/java/io/netty/handler/ssl/SslUtils.java#L320) because the promise has been marked as finished. Therefore `ctx.close()` is never called to close the channel.
[ "handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "handler/src/main/java/io/netty/handler/ssl/SslUtils.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java", "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "handler/src/main/java/io/netty/handler/ssl/SslUtils.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java index ecbf8263c18..05fcaffdfc3 100644 --- a/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/AbstractSniHandler.java @@ -81,7 +81,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t "not an SSL/TLS record: " + ByteBufUtil.hexDump(in)); in.skipBytes(in.readableBytes()); ctx.fireUserEventTriggered(new SniCompletionEvent(e)); - SslUtils.notifyHandshakeFailure(ctx, e, true); + SslUtils.handleHandshakeFailure(ctx, e, true); throw e; } if (len == SslUtils.NOT_ENOUGH_DATA || diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java index a5ebc363f37..1f22943caf4 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -865,7 +865,7 @@ private void finishWrap(ChannelHandlerContext ctx, ByteBuf out, ChannelPromise p /** * This method will not call - * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean)} or + * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}. * @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}. */ @@ -1002,7 +1002,7 @@ private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf i public void channelInactive(ChannelHandlerContext ctx) throws Exception { // Make sure to release SSLEngine, // and notify the handshake future if the connection has been closed during handshake. - setHandshakeFailure(ctx, CHANNEL_CLOSED, !outboundClosed, handshakeStarted); + setHandshakeFailure(ctx, CHANNEL_CLOSED, !outboundClosed, handshakeStarted, false); // Ensure we always notify the sslClosePromise as well notifyClosePromise(CHANNEL_CLOSED); @@ -1191,7 +1191,8 @@ private void handleUnwrapThrowable(ChannelHandlerContext ctx, Throwable cause) { logger.debug("SSLException during trying to call SSLEngine.wrap(...)" + " because of an previous SSLException, ignoring...", ex); } finally { - setHandshakeFailure(ctx, cause, true, false); + // ensure we always flush and close the channel. + setHandshakeFailure(ctx, cause, true, false, true); } PlatformDependent.throwException(cause); } @@ -1498,13 +1499,14 @@ private void setHandshakeSuccess() { * Notify all the handshake futures about the failure during the handshake. */ private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) { - setHandshakeFailure(ctx, cause, true, true); + setHandshakeFailure(ctx, cause, true, true, false); } /** * Notify all the handshake futures about the failure during the handshake. */ - private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound, boolean notify) { + private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound, + boolean notify, boolean alwaysFlushAndClose) { try { // Release all resources such as internal buffers that SSLEngine // is managing. @@ -1526,7 +1528,9 @@ private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boo } } } - notifyHandshakeFailure(cause, notify); + if (handshakePromise.tryFailure(cause) || alwaysFlushAndClose) { + SslUtils.handleHandshakeFailure(ctx, cause, notify); + } } finally { // Ensure we remove and fail all pending writes in all cases and so release memory quickly. releaseAndFailAll(cause); @@ -1539,12 +1543,6 @@ private void releaseAndFailAll(Throwable cause) { } } - private void notifyHandshakeFailure(Throwable cause, boolean notify) { - if (handshakePromise.tryFailure(cause)) { - SslUtils.notifyHandshakeFailure(ctx, cause, notify); - } - } - private void notifyClosePromise(Throwable cause) { if (cause == null) { if (sslClosePromise.trySuccess(ctx.channel())) { @@ -1725,7 +1723,9 @@ public void run() { return; } try { - notifyHandshakeFailure(HANDSHAKE_TIMED_OUT, true); + if (handshakePromise.tryFailure(HANDSHAKE_TIMED_OUT)) { + SslUtils.handleHandshakeFailure(ctx, HANDSHAKE_TIMED_OUT, true); + } } finally { releaseAndFailAll(HANDSHAKE_TIMED_OUT); } diff --git a/handler/src/main/java/io/netty/handler/ssl/SslUtils.java b/handler/src/main/java/io/netty/handler/ssl/SslUtils.java index 175238d41ed..3dd40fdf37b 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslUtils.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslUtils.java @@ -310,7 +310,7 @@ private static int getEncryptedPacketLength(ByteBuffer buffer) { return packetLength; } - static void notifyHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean notify) { + static void handleHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean notify) { // We have may haven written some parts of data before an exception was thrown so ensure we always flush. // See https://github.com/netty/netty/issues/3900#issuecomment-172481830 ctx.flush();
diff --git a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java index 5366de289f7..f3c31ed6dd4 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -599,4 +599,58 @@ protected void initChannel(Channel ch) throws Exception { ReferenceCountUtil.release(sslClientCtx); } } + + @Test(timeout = 10000) + public void testCloseOnHandshakeFailure() throws Exception { + final SelfSignedCertificate ssc = new SelfSignedCertificate(); + + final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.key(), ssc.cert()).build(); + final SslContext sslClientCtx = SslContextBuilder.forClient() + .trustManager(new SelfSignedCertificate().cert()) + .build(); + + EventLoopGroup group = new NioEventLoopGroup(1); + Channel sc = null; + Channel cc = null; + try { + LocalAddress address = new LocalAddress(getClass().getSimpleName() + ".testCloseOnHandshakeFailure"); + ServerBootstrap sb = new ServerBootstrap() + .group(group) + .channel(LocalServerChannel.class) + .childHandler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc())); + } + }); + sc = sb.bind(address).syncUninterruptibly().channel(); + + Bootstrap b = new Bootstrap() + .group(group) + .channel(LocalChannel.class) + .handler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc())); + } + }); + cc = b.connect(sc.localAddress()).syncUninterruptibly().channel(); + SslHandler handler = cc.pipeline().get(SslHandler.class); + handler.handshakeFuture().awaitUninterruptibly(); + assertFalse(handler.handshakeFuture().isSuccess()); + + cc.closeFuture().syncUninterruptibly(); + } finally { + if (cc != null) { + cc.close().syncUninterruptibly(); + } + if (sc != null) { + sc.close().syncUninterruptibly(); + } + group.shutdownGracefully(); + + ReferenceCountUtil.release(sslServerCtx); + ReferenceCountUtil.release(sslClientCtx); + } + } }
train
val
"2018-02-16T09:18:22"
"2018-02-16T00:48:14Z"
jianglai
val
netty/netty/7729_7730
netty/netty
netty/netty/7729
netty/netty/7730
[ "keyword_pr_to_issue" ]
1e5fafe44651e1e246a9a041cfbb453582e05491
ce241bd11ec26008a692b87391b94d8efe69069d
[ "Have the same issue. For now I fixed it with Increasing chunk size from 8k to 128k. In my case file is 4Mb only. It is reproduced only on specific VM.", "thanks for reporting. I have some questions...\r\n\r\n- Are you using `FileRegion` or do you cache the file in memory and write `ByteBuf`s (sounds like `ByteBuf` based upon how you are chunking and dealing with `FullHttpResponse`)?\r\n- Do you have an `SslHandler` in the pipeline?\r\n- Can you confirm if the data is actually being written (wire shark, LoggingHandler, etc...)\r\n- Are you not getting channelWritabilityChanged notifications when you would expect to?", "@Scottmitch I was using default Netty Static File example with small modifications. \r\n\r\nSslHandler is present and this part is used:\r\n\r\n```\r\nctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 8 * 1024)),\r\n ctx.newProgressivePromise());\r\n```\r\n\r\n> Can you confirm if the data is actually being written (wire shark, LoggingHandler, etc...)\r\n\r\nYes. Progress listener shows that server sends every time the random number of chunks (40-60% of the file, browser confirms that). Tested both via browser and curl. I wasn't able to debug locally as it was reproduced only on 1 VM.\r\n\r\n", "@doom369 - Can you list the precise steps you used to reproduce using the \"Netty Static File example\" (I'm assuming `HttpStaticFileServer`)? What file did you download, did you change any code, what browser were you using, what transport are you able to reproduce with (the example is hard coded to NIO, but this issue report is using EPOLL)?\r\n\r\nI tried with a 100mb file [1], and changed the low/high watermark to 8k/32k and was unable to reproduce with curl/chrome.\r\n\r\n[1] `dd if=/dev/zero of=LargeTestFile.img bs=1024 count=0 seek=$[1024*100]`", "@Scottmitch correct. I used handler from `HttpStaticFileServer` (just handler). My server also uses epoll along with openssl. Browser chrome. I'll try to cut off some minimal reproducer when I have some time.\r\n\r\nProblem file - https://www.dropbox.com/s/cfbjy029veybinx/main.344f92c975457d9a7419.js?dl=0\r\nSmaller files, css and html were downloaded fine.", "@Scottmitch - Sent you a reproducer check your mail.\r\n\r\n> Are you using FileRegion or do you cache the file in memory and write ByteBufs (sounds like ByteBuf based upon how you are chunking and dealing with FullHttpResponse)?\r\n\r\nIn memory\r\n\r\n> Do you have an SslHandler in the pipeline?\r\n\r\nIssue shows up with or without SslHandler\r\n\r\n> Can you confirm if the data is actually being written (wire shark, LoggingHandler, etc...)\r\n\r\nSometimes curl receives some of the data, other times, it receives none.\r\n\r\n> Are you not getting channelWritabilityChanged notifications when you would expect to?\r\n\r\nI assume I am not. Its hard to determine given my custom chunk encoder.", "@blucas - reproducer was very helpful to narrow in on the issue!", "@Scottmitch - You're welcome! Glad it helped!" ]
[ "@Scottmitch seems like the code is now basically the same as before here... Consider revert the change of the file ? Seems like the only change that is \"new\" is the final keyword", "consider reverting this as the code basically does the same as before.", "yes it is the same as before ... just 1 less LOC and byte code (see below). Maybe the JIT can optimize this ... but simple enough to do it in code.\r\n\r\n```java\r\n public void function1(boolean v) {\r\n if (!v) {\r\n return;\r\n }\r\n doWork();\r\n }\r\n\r\n public void function2(boolean v) {\r\n if (v) {\r\n doWork();\r\n }\r\n }\r\n```\r\n\r\n```\r\n public void function1(boolean);\r\n Code:\r\n 0: iload_1\r\n 1: ifne 5\r\n 4: return\r\n 5: aload_0\r\n 6: invokevirtual #6 // Method doWork:()V\r\n 9: return\r\n\r\n public void function2(boolean);\r\n Code:\r\n 0: iload_1\r\n 1: ifeq 8\r\n 4: aload_0\r\n 5: invokevirtual #6 // Method doWork:()V\r\n 8: return\r\n```", "@Scottmitch I guess at the end it really not matters.. So up to you." ]
"2018-02-18T22:12:38Z"
[ "defect" ]
Downloading large file halts during transfer
### Expected behavior When downloading a large file (50MB) from a netty based server, I expect to receive the entire file and that the download does not halt during the transfer. ### Actual behavior Download of file halts during the transfer. Transfer eventually terminates due to idle timeout. ### Steps to reproduce 1. Setup a Netty HTTP server using Epoll Edge Triggered 2. Set the low water mark to 8192 bytes (8k) and high to 32768 bytes (32k) 3. Transfer the file using 8k chunks, flushing when unwritable ### Minimal yet complete reproducer code (or URL to code) Will try to create one ### Netty version 4.1.21.Final ### JVM version (e.g. `java -version`) java version "1.7.0_80" Java(TM) SE Runtime Environment (build 1.7.0_80-b15) Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode) ### OS version (e.g. `uname -a`) Linux ### Notes FYI, downgrading to Netty 4.1.17.Final fixes the issue. I believe the issue has been introduced by https://github.com/netty/netty/commit/b215794de31f28355e4469fcc04782f55076c80c. I use a custom handler to chunk `FullHttpResponse` objects and send them outbound, so it may be an issue with that handler in conjunction with the netty commit mentioned above. /cc @Scottmitch Since you did the work on that commit
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java" ]
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java" ]
[ "testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketConditionalWritabilityTest.java", "transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollETSocketConditionalWritabilityTest.java", "transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollLTSocketConditionalWritabilityTest.java", "transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueETSocketConditionalWritabilityTest.java" ]
diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java index 758052db70b..8d3dc5bbcbd 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java @@ -507,14 +507,13 @@ EpollRecvByteAllocatorHandle newEpollHandle(RecvByteBufAllocator.ExtendedHandle } @Override - protected void flush0() { + protected final void flush0() { // Flush immediately only when there's no pending flush. // If there's a pending flush operation, event loop will call forceFlush() later, // and thus there's no need to call it now. - if (isFlagSet(Native.EPOLLOUT)) { - return; + if (!isFlagSet(Native.EPOLLOUT)) { + super.flush0(); } - super.flush0(); } /** diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java index e077b2903b7..0c0710f8fbf 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollStreamChannel.java @@ -445,6 +445,12 @@ protected void doWrite(ChannelOutboundBuffer in) throws Exception { } while (writeSpinCount > 0); if (writeSpinCount == 0) { + // It is possible that we have set EPOLLOUT, woken up by EPOLL because the socket is writable, and then use + // our write quantum. In this case we no longer want to set the EPOLLOUT flag because the socket is still + // writable (as far as we know). We will find out next time we attempt to write if the socket is writable + // and set the EPOLLOUT if necessary. + clearFlag(Native.EPOLLOUT); + // We used our writeSpin quantum, and should try to write again later. eventLoop().execute(flushTask); } else { diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java index df0cd6e7fa6..fbdbc4b71a6 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java @@ -498,6 +498,16 @@ public KQueueRecvByteAllocatorHandle recvBufAllocHandle() { return allocHandle; } + @Override + protected final void flush0() { + // Flush immediately only when there's no pending flush. + // If there's a pending flush operation, event loop will call forceFlush() later, + // and thus there's no need to call it now. + if (!writeFilterEnabled) { + super.flush0(); + } + } + final void executeReadReadyRunnable(ChannelConfig config) { if (readReadyRunnablePending || !isActive() || shouldBreakReadReady(config)) { return; diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java index 50d2cf9725f..ef5f48e820a 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueStreamChannel.java @@ -283,6 +283,12 @@ protected void doWrite(ChannelOutboundBuffer in) throws Exception { } while (writeSpinCount > 0); if (writeSpinCount == 0) { + // It is possible that we have set the write filter, woken up by KQUEUE because the socket is writable, and + // then use our write quantum. In this case we no longer want to set the write filter because the socket is + // still writable (as far as we know). We will find out next time we attempt to write if the socket is + // writable and set the write filter if necessary. + writeFilter(false); + // We used our writeSpin quantum, and should try to write again later. eventLoop().execute(flushTask); } else { diff --git a/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java b/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java index 8570b3d936a..5987dff2d7a 100644 --- a/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java +++ b/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java @@ -46,7 +46,12 @@ public abstract class AbstractNioByteChannel extends AbstractNioChannel { " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ", " + StringUtil.simpleClassName(FileRegion.class) + ')'; - private Runnable flushTask; + private final Runnable flushTask = new Runnable() { + @Override + public void run() { + flush(); + } + }; /** * Create a new instance @@ -266,16 +271,13 @@ protected final void incompleteWrite(boolean setOpWrite) { if (setOpWrite) { setOpWrite(); } else { + // It is possible that we have set the write OP, woken up by NIO because the socket is writable, and then + // use our write quantum. In this case we no longer want to set the write OP because the socket is still + // writable (as far as we know). We will find out next time we attempt to write if the socket is writable + // and set the write OP if necessary. + clearOpWrite(); + // Schedule flush again later so other tasks can be picked up in the meantime - Runnable flushTask = this.flushTask; - if (flushTask == null) { - flushTask = this.flushTask = new Runnable() { - @Override - public void run() { - flush(); - } - }; - } eventLoop().execute(flushTask); } } diff --git a/transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java b/transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java index f9ea574347b..01467b98361 100644 --- a/transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java +++ b/transport/src/main/java/io/netty/channel/nio/AbstractNioChannel.java @@ -356,10 +356,9 @@ protected final void flush0() { // Flush immediately only when there's no pending flush. // If there's a pending flush operation, event loop will call forceFlush() later, // and thus there's no need to call it now. - if (isFlushPending()) { - return; + if (!isFlushPending()) { + super.flush0(); } - super.flush0(); } @Override
diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketConditionalWritabilityTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketConditionalWritabilityTest.java new file mode 100644 index 00000000000..d5265a1a4c5 --- /dev/null +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketConditionalWritabilityTest.java @@ -0,0 +1,124 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.testsuite.transport.socket; + +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.WriteBufferWaterMark; +import io.netty.util.ReferenceCountUtil; +import org.junit.Test; + +import java.util.concurrent.CountDownLatch; + +public class SocketConditionalWritabilityTest extends AbstractSocketTest { + @Test(timeout = 30000) + public void testConditionalWritability() throws Throwable { + run(); + } + + public void testConditionalWritability(ServerBootstrap sb, Bootstrap cb) throws Throwable { + Channel serverChannel = null; + Channel clientChannel = null; + try { + final int expectedBytes = 100 * 1024 * 1024; + final int maxWriteChunkSize = 16 * 1024; + final CountDownLatch latch = new CountDownLatch(1); + sb.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 16 * 1024)); + sb.childHandler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(new ChannelDuplexHandler() { + private int bytesWritten; + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ReferenceCountUtil.release(msg); + writeRemainingBytes(ctx); + } + + @Override + public void flush(ChannelHandlerContext ctx) { + if (ctx.channel().isWritable()) { + writeRemainingBytes(ctx); + } else { + ctx.flush(); + } + } + + @Override + public void channelWritabilityChanged(ChannelHandlerContext ctx) { + if (ctx.channel().isWritable()) { + writeRemainingBytes(ctx); + } + ctx.fireChannelWritabilityChanged(); + } + + private void writeRemainingBytes(ChannelHandlerContext ctx) { + while (ctx.channel().isWritable() && bytesWritten < expectedBytes) { + int chunkSize = Math.min(expectedBytes - bytesWritten, maxWriteChunkSize); + bytesWritten += chunkSize; + ctx.write(ctx.alloc().buffer(chunkSize).writeZero(chunkSize)); + } + ctx.flush(); + } + }); + } + }); + + serverChannel = sb.bind().syncUninterruptibly().channel(); + + cb.handler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + private int totalRead; + @Override + public void channelActive(ChannelHandlerContext ctx) { + ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(0)); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + if (msg instanceof ByteBuf) { + totalRead += ((ByteBuf) msg).readableBytes(); + if (totalRead == expectedBytes) { + latch.countDown(); + } + } + ReferenceCountUtil.release(msg); + } + }); + } + }); + clientChannel = cb.connect(serverChannel.localAddress()).syncUninterruptibly().channel(); + latch.await(); + } finally { + if (serverChannel != null) { + serverChannel.close(); + } + if (clientChannel != null) { + clientChannel.close(); + } + } + } +} diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollETSocketConditionalWritabilityTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollETSocketConditionalWritabilityTest.java new file mode 100644 index 00000000000..773e3d63c83 --- /dev/null +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollETSocketConditionalWritabilityTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.epoll; + +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBufAllocator; +import io.netty.testsuite.transport.TestsuitePermutation; +import io.netty.testsuite.transport.socket.SocketConditionalWritabilityTest; + +import java.util.List; + +public class EpollETSocketConditionalWritabilityTest extends SocketConditionalWritabilityTest { + @Override + protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { + return EpollSocketTestPermutation.INSTANCE.socket(); + } + + @Override + protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { + super.configure(bootstrap, bootstrap2, allocator); + bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED) + .childOption(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); + bootstrap2.option(EpollChannelOption.EPOLL_MODE, EpollMode.EDGE_TRIGGERED); + } +} diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollLTSocketConditionalWritabilityTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollLTSocketConditionalWritabilityTest.java new file mode 100644 index 00000000000..31cb81964da --- /dev/null +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollLTSocketConditionalWritabilityTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.epoll; + +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBufAllocator; +import io.netty.testsuite.transport.TestsuitePermutation; +import io.netty.testsuite.transport.socket.SocketConditionalWritabilityTest; + +import java.util.List; + +public class EpollLTSocketConditionalWritabilityTest extends SocketConditionalWritabilityTest { + @Override + protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { + return EpollSocketTestPermutation.INSTANCE.socket(); + } + + @Override + protected void configure(ServerBootstrap bootstrap, Bootstrap bootstrap2, ByteBufAllocator allocator) { + super.configure(bootstrap, bootstrap2, allocator); + bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED) + .childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); + bootstrap2.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); + } +} diff --git a/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueETSocketConditionalWritabilityTest.java b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueETSocketConditionalWritabilityTest.java new file mode 100644 index 00000000000..1c3da7485ef --- /dev/null +++ b/transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueETSocketConditionalWritabilityTest.java @@ -0,0 +1,30 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.kqueue; + +import io.netty.bootstrap.Bootstrap; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.testsuite.transport.TestsuitePermutation; +import io.netty.testsuite.transport.socket.SocketConditionalWritabilityTest; + +import java.util.List; + +public class KQueueETSocketConditionalWritabilityTest extends SocketConditionalWritabilityTest { + @Override + protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { + return KQueueSocketTestPermutation.INSTANCE.socket(); + } +}
train
val
"2018-02-17T07:47:44"
"2018-02-18T08:35:07Z"
blucas
val
netty/netty/7760_7765
netty/netty
netty/netty/7760
netty/netty/7765
[ "timestamp(timedelta=0.0, similarity=0.90353806799172)" ]
0a8e1aaf19dc85830478041cb57b308b764cfacd
48df2f66b858f3ce2a0a069dafb1332da55c47f9
[ "@ivankelly this sounds clearly like a bug... Let me check as soon as I have a few cycles or if you like you could also try to provide a PR .", "@normanmaurer I had a quick look. The logic looks sound. If I get more time, I'll look again. It's going to be something to do with something being added to turn it negative.", "@ivankelly yep sounds like it... looking now", "@ivankelly ok I know whats wrong... writing a fix now", ":+1: ", "@ivankelly https://github.com/netty/netty/pull/7765" ]
[ "@normanmaurer what about the case when someone intentionally passes a negative value into delay?", "@johnou hmm good question. I am not sure this is expected but let me add a check as it was \"allowed\" before." ]
"2018-03-02T09:02:20Z"
[ "defect" ]
HashedWheelTimer doesn't handle very large values
### Expected behavior If I set a timeout with Long.MAX_VALUE (effectively trying to disable it), it should never run. ### Actual behavior It runs. It runs a lot. ### Steps to reproduce ``` @Test public void testMassiveTimeout() throws InterruptedException { final Timer timer = new HashedWheelTimer(); final CountDownLatch barrier = new CountDownLatch(1); final Timeout timeout = timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { fail("This should not have run"); barrier.countDown(); } }, Long.MAX_VALUE, TimeUnit.SECONDS); assertFalse(barrier.await(3, TimeUnit.SECONDS)); assertFalse("timer should not expire", timeout.isExpired()); timer.stop(); } ``` ### Netty version Behaviour observed in 4.1.21.Final Tested on 4.1 branch from January 2 (062d9269120bac0064408025b78788613d41d36d) ### JVM version (e.g. `java -version`) openjdk version "1.8.0_151" OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-1~deb9u1-b12) OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode) ### OS version (e.g. `uname -a`) Linux eshmun 4.9.0-5-amd64 #1 SMP Debian 4.9.65-3+deb9u2 (2018-01-04) x86_64 GNU/Linux
[ "common/src/main/java/io/netty/util/HashedWheelTimer.java" ]
[ "common/src/main/java/io/netty/util/HashedWheelTimer.java" ]
[ "common/src/test/java/io/netty/util/HashedWheelTimerTest.java" ]
diff --git a/common/src/main/java/io/netty/util/HashedWheelTimer.java b/common/src/main/java/io/netty/util/HashedWheelTimer.java index 77d956b12bb..b62ace4695e 100644 --- a/common/src/main/java/io/netty/util/HashedWheelTimer.java +++ b/common/src/main/java/io/netty/util/HashedWheelTimer.java @@ -419,6 +419,11 @@ public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { // Add the timeout to the timeout queue which will be processed on the next tick. // During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket. long deadline = System.nanoTime() + unit.toNanos(delay) - startTime; + + // Guard against overflow. + if (delay > 0 && deadline < 0) { + deadline = Long.MAX_VALUE; + } HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline); timeouts.add(timeout); return timeout;
diff --git a/common/src/test/java/io/netty/util/HashedWheelTimerTest.java b/common/src/test/java/io/netty/util/HashedWheelTimerTest.java index e1a7bccc6ef..2bf1c34819e 100644 --- a/common/src/test/java/io/netty/util/HashedWheelTimerTest.java +++ b/common/src/test/java/io/netty/util/HashedWheelTimerTest.java @@ -230,6 +230,21 @@ public void reportPendingTimeouts() throws InterruptedException { timer.stop(); } + @Test + public void testOverflow() throws InterruptedException { + final HashedWheelTimer timer = new HashedWheelTimer(); + final CountDownLatch latch = new CountDownLatch(1); + Timeout timeout = timer.newTimeout(new TimerTask() { + @Override + public void run(Timeout timeout) { + latch.countDown(); + } + }, Long.MAX_VALUE, TimeUnit.MILLISECONDS); + assertFalse(latch.await(1, TimeUnit.SECONDS)); + timeout.cancel(); + timer.stop(); + } + private static TimerTask createNoOpTimerTask() { return new TimerTask() { @Override
train
val
"2018-03-02T02:09:40"
"2018-03-01T14:47:30Z"
ivankelly
val
netty/netty/7752_7774
netty/netty
netty/netty/7752
netty/netty/7774
[ "timestamp(timedelta=14.0, similarity=0.8586944922579707)" ]
6eb9674bf5ded128cb230a31987f14816b7f1886
f6251c8256d8ce3fb6fb76df23e477caa15f627b
[ "@ldaley sorry took me a while due travelling / meetings etc.\r\n\r\nhttps://github.com/netty/netty/pull/7773\r\n", "@normanmaurer no problem sir. Appreciated all the same.", "And https://github.com/netty/netty/pull/7774", "Fixed" ]
[]
"2018-03-10T09:28:42Z"
[]
IovArray.add(ByteBuf) throws if buffer is a composite of a single direct buffer
### Expected behavior Not throwing unhandled `UnsupportedOperationException`. ### Actual behavior Method throws unhandled `UnsupportedOperationException` which causes channel write operations to fail. ### Steps to reproduce The problem is here: https://github.com/netty/netty/blob/4.1/transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java#L96 If `buf` is a `FixedCompositeByteBuf` with one direct buffer component, it will return `nioBufferCount() == 1` and `memoryAddress()` will throw `UnsupportedOperationException`. I can see two possible, complimentary fixes: 1. Make `memoryAddress()` work for composites that are one direct buffer 2. Change this if branch condition to `buf.nioBufferCount() == 1 && buf.hasMemoryAddress()` Here's a stack trace showing the problem: ``` io.netty.channel.socket.ChannelOutputShutdownException: Channel output shutdown at io.netty.channel.AbstractChannel$AbstractUnsafe.shutdownOutput(AbstractChannel.java:641) at io.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:948) at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.flush0(AbstractEpollChannel.java:543) at io.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:901) at io.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1321) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) at io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.flush(CombinedChannelDuplexHandler.java:533) at io.netty.channel.ChannelOutboundHandlerAdapter.flush(ChannelOutboundHandlerAdapter.java:115) at io.netty.channel.CombinedChannelDuplexHandler.flush(CombinedChannelDuplexHandler.java:358) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) at io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) at io.netty.channel.ChannelDuplexHandler.flush(ChannelDuplexHandler.java:117) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush(AbstractChannelHandlerContext.java:802) at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:814) at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:794) at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:831) at io.netty.channel.DefaultChannelPipeline.writeAndFlush(DefaultChannelPipeline.java:1041) at io.netty.channel.AbstractChannel.writeAndFlush(AbstractChannel.java:300) at ratpack.http.client.internal.RequestActionSupport.lambda$send$4(RequestActionSupport.java:137) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) at io.netty.util.concurrent.DefaultPromise.notifyListenerWithStackOverFlowProtection(DefaultPromise.java:450) at io.netty.util.concurrent.DefaultPromise.notifyListener(DefaultPromise.java:409) at io.netty.util.concurrent.CompleteFuture.addListener(CompleteFuture.java:49) at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:56) at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:27) at ratpack.http.client.internal.RequestActionSupport.send(RequestActionSupport.java:135) at ratpack.http.client.internal.RequestActionSupport.lambda$null$0(RequestActionSupport.java:99) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) at io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104) at io.netty.channel.DefaultChannelPromise.trySuccess(DefaultChannelPromise.java:82) at io.netty.channel.AbstractChannel$AbstractUnsafe.safeSetSuccess(AbstractChannel.java:978) at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:512) at io.netty.channel.AbstractChannel$AbstractUnsafe.access$200(AbstractChannel.java:423) at io.netty.channel.AbstractChannel$AbstractUnsafe$1.run(AbstractChannel.java:482) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403) at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:309) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at ratpack.exec.internal.DefaultExecController$ExecControllerBindingThreadFactory.lambda$newThread$0(DefaultExecController.java:136) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.UnsupportedOperationException: null at io.netty.buffer.FixedCompositeByteBuf.memoryAddress(FixedCompositeByteBuf.java:635) at io.netty.buffer.ReadOnlyByteBuf.memoryAddress(ReadOnlyByteBuf.java:121) at io.netty.channel.unix.IovArray.add(IovArray.java:94) at io.netty.channel.unix.IovArray.processMessage(IovArray.java:209) at io.netty.channel.ChannelOutboundBuffer.forEachFlushedMessage(ChannelOutboundBuffer.java:738) at io.netty.channel.epoll.AbstractEpollStreamChannel.doWriteMultiple(AbstractEpollStreamChannel.java:500) at io.netty.channel.epoll.AbstractEpollStreamChannel.doWrite(AbstractEpollStreamChannel.java:442) at io.netty.channel.AbstractChannel$AbstractUnsafe.flush0(AbstractChannel.java:934) at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.flush0(AbstractEpollChannel.java:543) at io.netty.channel.AbstractChannel$AbstractUnsafe.flush(AbstractChannel.java:901) at io.netty.channel.DefaultChannelPipeline$HeadContext.flush(DefaultChannelPipeline.java:1321) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) at io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.flush(CombinedChannelDuplexHandler.java:533) at io.netty.channel.ChannelOutboundHandlerAdapter.flush(ChannelOutboundHandlerAdapter.java:115) at io.netty.channel.CombinedChannelDuplexHandler.flush(CombinedChannelDuplexHandler.java:358) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush(AbstractChannelHandlerContext.java:768) at io.netty.channel.AbstractChannelHandlerContext.flush(AbstractChannelHandlerContext.java:749) at io.netty.channel.ChannelDuplexHandler.flush(ChannelDuplexHandler.java:117) at io.netty.channel.AbstractChannelHandlerContext.invokeFlush0(AbstractChannelHandlerContext.java:776) at io.netty.channel.AbstractChannelHandlerContext.invokeWriteAndFlush(AbstractChannelHandlerContext.java:802) at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:814) at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:794) at io.netty.channel.AbstractChannelHandlerContext.writeAndFlush(AbstractChannelHandlerContext.java:831) at io.netty.channel.DefaultChannelPipeline.writeAndFlush(DefaultChannelPipeline.java:1041) at io.netty.channel.AbstractChannel.writeAndFlush(AbstractChannel.java:300) at ratpack.http.client.internal.RequestActionSupport.lambda$send$4(RequestActionSupport.java:137) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) at io.netty.util.concurrent.DefaultPromise.notifyListenerWithStackOverFlowProtection(DefaultPromise.java:450) at io.netty.util.concurrent.DefaultPromise.notifyListener(DefaultPromise.java:409) at io.netty.util.concurrent.CompleteFuture.addListener(CompleteFuture.java:49) at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:56) at io.netty.channel.CompleteChannelFuture.addListener(CompleteChannelFuture.java:27) at ratpack.http.client.internal.RequestActionSupport.send(RequestActionSupport.java:135) at ratpack.http.client.internal.RequestActionSupport.lambda$null$0(RequestActionSupport.java:99) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:507) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:481) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:420) at io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104) at io.netty.channel.DefaultChannelPromise.trySuccess(DefaultChannelPromise.java:82) at io.netty.channel.AbstractChannel$AbstractUnsafe.safeSetSuccess(AbstractChannel.java:978) at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:512) at io.netty.channel.AbstractChannel$AbstractUnsafe.access$200(AbstractChannel.java:423) at io.netty.channel.AbstractChannel$AbstractUnsafe$1.run(AbstractChannel.java:482) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403) at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:309) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) ``` ### Netty version 4.1.21.
[ "transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java" ]
[ "transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java" ]
[]
diff --git a/transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java b/transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java index 3e0946e255e..151abe609ae 100644 --- a/transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java +++ b/transport-native-unix-common/src/main/java/io/netty/channel/unix/IovArray.java @@ -91,7 +91,7 @@ public boolean add(ByteBuf buf) { if (count == IOV_MAX) { // No more room! return false; - } else if (buf.nioBufferCount() == 1) { + } else if (buf.hasMemoryAddress() && buf.nioBufferCount() == 1) { final int len = buf.readableBytes(); return len == 0 || add(buf.memoryAddress(), buf.readerIndex(), len); } else {
null
train
val
"2018-03-10T03:45:02"
"2018-02-27T01:04:22Z"
ldaley
val
netty/netty/7781_7782
netty/netty
netty/netty/7781
netty/netty/7782
[ "timestamp(timedelta=0.0, similarity=0.8447407530444115)" ]
f6251c8256d8ce3fb6fb76df23e477caa15f627b
de082bf4c719f177cb068e01511bc1c69bde4cbf
[ "Will have a look", "@trustin please check the PR." ]
[]
"2018-03-15T10:23:10Z"
[ "defect" ]
ResourceLeakDetector does not retain the initial record
### Expected behavior The leak report printed by `ResourceLeakDetector` retains the stack trace of the moment the buffer was created. ### Actual behavior The record with `Created at:` heading is not actually the creation record, e.g. ``` Created at: io.netty.buffer.AdvancedLeakAwareByteBuf.writeBytes(AdvancedLeakAwareByteBuf.java:616) ... ``` ### Steps to reproduce Not sure, but probably write an app that generates a lot of access records and leak? ### Minimal yet complete reproducer code (or URL to code) Sorry, no. ### Netty version 4.1.22 ### JVM version (e.g. `java -version`) ``` java version "1.8.0_144" Java(TM) SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode) ``` ### OS version (e.g. `uname -a`) ``` Linux infinity 4.14.25-1-lts #1 SMP Fri Mar 9 22:02:42 CET 2018 x86_64 GNU/Linux ```
[ "common/src/main/java/io/netty/util/ResourceLeakDetector.java" ]
[ "common/src/main/java/io/netty/util/ResourceLeakDetector.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/ResourceLeakDetector.java b/common/src/main/java/io/netty/util/ResourceLeakDetector.java index 3872c07d1cc..c29320adb7d 100644 --- a/common/src/main/java/io/netty/util/ResourceLeakDetector.java +++ b/common/src/main/java/io/netty/util/ResourceLeakDetector.java @@ -369,7 +369,8 @@ private static final class DefaultResourceLeak<T> // be collected via the WeakReference. trackedHash = System.identityHashCode(referent); allLeaks.put(this, LeakEntry.INSTANCE); - headUpdater.set(this, Record.BOTTOM); + // Create a new Record so we always have the creation stacktrace included. + headUpdater.set(this, new Record(Record.BOTTOM)); this.allLeaks = allLeaks; }
null
val
val
"2018-03-13T08:51:01"
"2018-03-15T05:59:37Z"
trustin
val
netty/netty/7749_7793
netty/netty
netty/netty/7749
netty/netty/7793
[ "timestamp(timedelta=35.0, similarity=0.9344906068123431)" ]
8189399e9d6a2e17e8d5b4665c86efb696792f56
c0ae5e697c3c4fdf81f0cfc199d18aacd3b8ecba
[ "Fixed by https://github.com/netty/netty/pull/7793" ]
[ "- build -> build a\r\n- DnsNameResolver -> DnsNameResolver. (dot)", "@trustin 🤔shoud other 2 `IllegalStateException` be updated with a trailing dot? ", "This won't work. If someone makes a DnsNameResolverBuilder and then calls build, and then subsequently modifies the builder, the channelFactory of DnsAddressResolverGroup will change. \r\n\r\nThat would be unexpected.", "@carl-mastrangelo Not sure I follow. If you passed `DnsNameResolverBuilder` to create a `DnsAddressResolverGroup`, what you would expect from changing `channelFactory` on the builder you've used? ", "@trustin Fixed the message.", "I wouldn't expect the DnsAddressResolverGroup to use a different channel factory if the DnsNameResolverBuilder changed channelFactory. That is currently possible as is.", "@carl-mastrangelo Would a deep copy of the builder meet your expectations? This will prevent mutations propagation, but it might be not expected as well. ", "a deep copy would be good. Immutability is highly recommended. This is Effective Java item 15 in the the 2nd edition.", "@carl-mastrangelo Updated.", "A rule of thumb is:\r\n\r\n- Do not end with a dot if it's not a sentence, e.g. 'not a number'\r\n- End with a dot if it's a sentence, e.g. 'It is not a number.'\r\n- End with a dot if it's not a sentence but followed by a sentence, e.g. 'not a number. It has to be a number.;", "@trustin Got it, thanks! " ]
"2018-03-19T09:00:26Z"
[]
Proposal: DnsAddressResolverGroup to use injectable DnsNameResolverBuilder
### Expected behavior It should be possible to create `DnsAddressResolverGroup` having `DnsNameResolverBuilder` ready-to-go. ### Actual behavior Right now, if I want setup custom settings for `DnsAddressResolver` I need to sub-class `DnsAddressResolverGroup` and override `newNameResolver` [method](https://github.com/netty/netty/blob/06dcca1dbcc048b6ce7d954e4ecdf1d3ed6af034/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java#L97) as it creates new `DnsNameResolverBuilder` with "almost" default settings internally. Ideally, I want to instantiate `DnsNameResolverBuilder` by my own and pass it to the `DnsAddressResolverGroup` as an argument. More than that, I don't need `channelFactory` and `nameServerProvider` being carried over `DnsAddressResolverGroup`: I can set them directly to the `DnsNameResolverBuilder` instance. It probably would be even easier to create a new `AddressResolverGroup` implementation to work this way, but `InflightNameResolver` is not allowed to be used from the outside of the package, so if the user wants to benefit from it, it should follow `DnsAddressResolverGroup` API and override `newNameResolver`. ### Netty version 4.1.* ### Proposal There're 2 options here: 1. Upgrade `DnsAddressResolverGroup` with a new constructor ```java public DnsAddressResolverGroup(DnsNameResolverBuilder builder); ``` and appropriate checker if we have `DnsNameResolverBuilder` or we need to create a new one. 2. Create a new `AddressResolverGroup` implementation, like `PluggableDnsAddressResolverGroup` (? naming is hard). What do you think? Happy to create a PR if there are no objections here.
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java", "resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java", "resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java" ]
[ "resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java" ]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java index fb306082320..303c42a0988 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java @@ -42,23 +42,27 @@ @UnstableApi public class DnsAddressResolverGroup extends AddressResolverGroup<InetSocketAddress> { - private final ChannelFactory<? extends DatagramChannel> channelFactory; - private final DnsServerAddressStreamProvider nameServerProvider; + private final DnsNameResolverBuilder dnsResolverBuilder; private final ConcurrentMap<String, Promise<InetAddress>> resolvesInProgress = newConcurrentHashMap(); private final ConcurrentMap<String, Promise<List<InetAddress>>> resolveAllsInProgress = newConcurrentHashMap(); + public DnsAddressResolverGroup(DnsNameResolverBuilder dnsResolverBuilder) { + this.dnsResolverBuilder = dnsResolverBuilder.copy(); + } + public DnsAddressResolverGroup( Class<? extends DatagramChannel> channelType, DnsServerAddressStreamProvider nameServerProvider) { - this(new ReflectiveChannelFactory<DatagramChannel>(channelType), nameServerProvider); + this(new DnsNameResolverBuilder()); + dnsResolverBuilder.channelType(channelType).nameServerProvider(nameServerProvider); } public DnsAddressResolverGroup( ChannelFactory<? extends DatagramChannel> channelFactory, DnsServerAddressStreamProvider nameServerProvider) { - this.channelFactory = channelFactory; - this.nameServerProvider = nameServerProvider; + this(new DnsNameResolverBuilder()); + dnsResolverBuilder.channelFactory(channelFactory).nameServerProvider(nameServerProvider); } @SuppressWarnings("deprecation") @@ -70,7 +74,11 @@ protected final AddressResolver<InetSocketAddress> newResolver(EventExecutor exe " (expected: " + StringUtil.simpleClassName(EventLoop.class)); } - return newResolver((EventLoop) executor, channelFactory, nameServerProvider); + // we don't really need to pass channelFactory and nameServerProvider separately, + // but still keep this to ensure backward compatibility with (potentially) override methods + return newResolver((EventLoop) executor, + dnsResolverBuilder.channelFactory(), + dnsResolverBuilder.nameServerProvider()); } /** @@ -98,7 +106,9 @@ protected NameResolver<InetAddress> newNameResolver(EventLoop eventLoop, ChannelFactory<? extends DatagramChannel> channelFactory, DnsServerAddressStreamProvider nameServerProvider) throws Exception { - return new DnsNameResolverBuilder(eventLoop) + // once again, channelFactory and nameServerProvider are most probably set in builder already, + // but I do reassign them again to avoid corner cases with override methods + return dnsResolverBuilder.eventLoop(eventLoop) .channelFactory(channelFactory) .nameServerProvider(nameServerProvider) .build(); diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java index 8ccf7c308f9..a5df3409dfe 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java @@ -25,6 +25,7 @@ import io.netty.util.internal.UnstableApi; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static io.netty.resolver.dns.DnsServerAddressStreamProviders.platformDefault; @@ -36,7 +37,7 @@ */ @UnstableApi public final class DnsNameResolverBuilder { - private final EventLoop eventLoop; + private EventLoop eventLoop; private ChannelFactory<? extends DatagramChannel> channelFactory; private DnsCache resolveCache; private DnsCache authoritativeDnsServerCache; @@ -58,14 +59,35 @@ public final class DnsNameResolverBuilder { private int ndots = -1; private boolean decodeIdn = true; + /** + * Creates a new builder. + */ + public DnsNameResolverBuilder() { + } + /** * Creates a new builder. * - * @param eventLoop the {@link EventLoop} the {@link EventLoop} which will perform the communication with the DNS + * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS * servers. */ public DnsNameResolverBuilder(EventLoop eventLoop) { + eventLoop(eventLoop); + } + + /** + * Sets the {@link EventLoop} which will perform the communication with the DNS servers. + * + * @param eventLoop the {@link EventLoop} + * @return {@code this} + */ + public DnsNameResolverBuilder eventLoop(EventLoop eventLoop) { this.eventLoop = eventLoop; + return this; + } + + protected ChannelFactory<? extends DatagramChannel> channelFactory() { + return this.channelFactory; } /** @@ -274,6 +296,10 @@ public DnsNameResolverBuilder hostsFileEntriesResolver(HostsFileEntriesResolver return this; } + protected DnsServerAddressStreamProvider nameServerProvider() { + return this.dnsServerAddressStreamProvider; + } + /** * Set the {@link DnsServerAddressStreamProvider} which is used to determine which DNS server is used to resolve * each hostname. @@ -347,6 +373,10 @@ public DnsNameResolverBuilder decodeIdn(boolean decodeIdn) { * @return a {@link DnsNameResolver} */ public DnsNameResolver build() { + if (eventLoop == null) { + throw new IllegalStateException("eventLoop should be specified to build a DnsNameResolver."); + } + if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { throw new IllegalStateException("resolveCache and TTLs are mutually exclusive"); } @@ -377,4 +407,63 @@ public DnsNameResolver build() { ndots, decodeIdn); } + + /** + * Creates a copy of this {@link DnsNameResolverBuilder} + * + * @return {@link DnsNameResolverBuilder} + */ + public DnsNameResolverBuilder copy() { + DnsNameResolverBuilder copiedBuilder = new DnsNameResolverBuilder(); + + if (eventLoop != null) { + copiedBuilder.eventLoop(eventLoop); + } + + if (channelFactory != null) { + copiedBuilder.channelFactory(channelFactory); + } + + if (resolveCache != null) { + copiedBuilder.resolveCache(resolveCache); + } + + if (maxTtl != null && minTtl != null) { + copiedBuilder.ttl(minTtl, maxTtl); + } + + if (negativeTtl != null) { + copiedBuilder.negativeTtl(negativeTtl); + } + + if (authoritativeDnsServerCache != null) { + copiedBuilder.authoritativeDnsServerCache(authoritativeDnsServerCache); + } + + if (dnsQueryLifecycleObserverFactory != null) { + copiedBuilder.dnsQueryLifecycleObserverFactory(dnsQueryLifecycleObserverFactory); + } + + copiedBuilder.queryTimeoutMillis(queryTimeoutMillis); + copiedBuilder.resolvedAddressTypes(resolvedAddressTypes); + copiedBuilder.recursionDesired(recursionDesired); + copiedBuilder.maxQueriesPerResolve(maxQueriesPerResolve); + copiedBuilder.traceEnabled(traceEnabled); + copiedBuilder.maxPayloadSize(maxPayloadSize); + copiedBuilder.optResourceEnabled(optResourceEnabled); + copiedBuilder.hostsFileEntriesResolver(hostsFileEntriesResolver); + + if (dnsServerAddressStreamProvider != null) { + copiedBuilder.nameServerProvider(dnsServerAddressStreamProvider); + } + + if (searchDomains != null) { + copiedBuilder.searchDomains(Arrays.asList(searchDomains)); + } + + copiedBuilder.ndots(ndots); + copiedBuilder.decodeIdn(decodeIdn); + + return copiedBuilder; + } } diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java b/resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java index 1fc072baa7c..68c14fec61f 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/RoundRobinDnsAddressResolverGroup.java @@ -36,6 +36,10 @@ @UnstableApi public class RoundRobinDnsAddressResolverGroup extends DnsAddressResolverGroup { + public RoundRobinDnsAddressResolverGroup(DnsNameResolverBuilder dnsResolverBuilder) { + super(dnsResolverBuilder); + } + public RoundRobinDnsAddressResolverGroup( Class<? extends DatagramChannel> channelType, DnsServerAddressStreamProvider nameServerProvider) {
diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java index 805121c7304..b2f5c3a9ee5 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java @@ -18,6 +18,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; import io.netty.channel.AddressedEnvelope; +import io.netty.channel.ChannelFactory; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; @@ -1474,4 +1475,20 @@ public DnsCacheEntry cache(String hostname, DnsRecord[] additionals, Throwable c assertTrue(DnsNameResolver.isTransportOrTimeoutError(cause)); resolver.close(); } + + @Test + public void testDnsNameResolverBuilderCopy() { + ChannelFactory<DatagramChannel> channelFactory = + new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class); + DnsNameResolverBuilder builder = new DnsNameResolverBuilder(group.next()) + .channelFactory(channelFactory); + DnsNameResolverBuilder copiedBuilder = builder.copy(); + + // change channel factory does not propagate to previously made copy + ChannelFactory<DatagramChannel> newChannelFactory = + new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class); + builder.channelFactory(newChannelFactory); + assertEquals(channelFactory, copiedBuilder.channelFactory()); + assertEquals(newChannelFactory, builder.channelFactory()); + } }
train
val
"2018-03-23T07:39:17"
"2018-02-26T12:00:12Z"
kachayev
val
netty/netty/7785_7800
netty/netty
netty/netty/7785
netty/netty/7800
[ "timestamp(timedelta=0.0, similarity=0.9347780009242861)" ]
6e6cfa0604aa578b52ed5d72ac954f040fadffa3
76c5f6cd03c7c57fab823d3b0774b56c3ed97fc3
[ "@gustavonalle PRs welcome", "Working on it" ]
[]
"2018-03-20T16:19:30Z"
[]
Enable different Cors rules per origin
### Expected behavior It'd be nice to configure the CorsHandler so that I can specify a different set of permissions based on the Origin. Example, if origin is http://localhost:8080/ I'd like to allow all methods and auth, but for a certain external Url I'd like to be stricter and limit it for GET only. ### Actual behavior Current the CorsHandler is configured with a single CorsConfig object that specifies the permissions for one or more origin; CorsConfig's ```allowedRequestMethods```, ```allowedRequestHeaders``` and others apply to all origins. ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.22.Final ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java", "common/src/main/java/io/netty/util/internal/ObjectUtil.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java", "common/src/main/java/io/netty/util/internal/ObjectUtil.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java index f4b5552b724..1c27863d5dc 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java @@ -30,15 +30,19 @@ import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; -import static io.netty.handler.codec.http.HttpMethod.*; -import static io.netty.handler.codec.http.HttpResponseStatus.*; -import static io.netty.util.ReferenceCountUtil.*; -import static io.netty.util.internal.ObjectUtil.checkNotNull; +import java.util.Collections; +import java.util.List; + +import static io.netty.handler.codec.http.HttpMethod.OPTIONS; +import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.util.ReferenceCountUtil.release; +import static io.netty.util.internal.ObjectUtil.checkNonEmpty; /** * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests. * <p> - * This handler can be configured using a {@link CorsConfig}, please + * This handler can be configured using one or more {@link CorsConfig}, please * refer to this class for details about the configuration options available. */ public class CorsHandler extends ChannelDuplexHandler { @@ -46,26 +50,43 @@ public class CorsHandler extends ChannelDuplexHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(CorsHandler.class); private static final String ANY_ORIGIN = "*"; private static final String NULL_ORIGIN = "null"; - private final CorsConfig config; + private CorsConfig config; private HttpRequest request; + private final List<CorsConfig> configList; + private boolean isShortCircuit; /** - * Creates a new instance with the specified {@link CorsConfig}. + * Creates a new instance with a single {@link CorsConfig}. */ public CorsHandler(final CorsConfig config) { - this.config = checkNotNull(config, "config"); + this(Collections.singletonList(config), config.isShortCircuit()); + } + + /** + * Creates a new instance with the specified config list. If more than one + * config matches a certain origin, the first in the List will be used. + * + * @param configList List of {@link CorsConfig} + * @param isShortCircuit Same as {@link CorsConfig#shortCircuit} but applicable to all supplied configs. + */ + public CorsHandler(final List<CorsConfig> configList, boolean isShortCircuit) { + checkNonEmpty(configList, "configList"); + this.configList = configList; + this.isShortCircuit = isShortCircuit; } @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { - if (config.isCorsSupportEnabled() && msg instanceof HttpRequest) { + if (msg instanceof HttpRequest) { request = (HttpRequest) msg; + final String origin = request.headers().get(HttpHeaderNames.ORIGIN); + config = getForOrigin(origin); if (isPreflightRequest(request)) { handlePreflight(ctx, request); return; } - if (config.isShortCircuit() && !validateOrigin()) { + if (isShortCircuit && !(origin == null || config != null)) { forbidden(ctx, request); return; } @@ -99,6 +120,21 @@ private void setPreflightHeaders(final HttpResponse response) { response.headers().add(config.preflightResponseHeaders()); } + private CorsConfig getForOrigin(String requestOrigin) { + for (CorsConfig corsConfig : configList) { + if (corsConfig.isAnyOriginSupported()) { + return corsConfig; + } + if (corsConfig.origins().contains(requestOrigin)) { + return corsConfig; + } + if (corsConfig.isNullOriginAllowed() || NULL_ORIGIN.equals(requestOrigin)) { + return corsConfig; + } + } + return null; + } + private boolean setOrigin(final HttpResponse response) { final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (origin != null) { @@ -125,24 +161,6 @@ private boolean setOrigin(final HttpResponse response) { return false; } - private boolean validateOrigin() { - if (config.isAnyOriginSupported()) { - return true; - } - - final String origin = request.headers().get(HttpHeaderNames.ORIGIN); - if (origin == null) { - // Not a CORS request so we cannot validate it. It may be a non CORS request. - return true; - } - - if ("null".equals(origin) && config.isNullOriginAllowed()) { - return true; - } - - return config.origins().contains(origin); - } - private void echoRequestOrigin(final HttpResponse response) { setOrigin(response, request.headers().get(HttpHeaderNames.ORIGIN)); } @@ -198,7 +216,7 @@ private void setMaxAge(final HttpResponse response) { @Override public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception { - if (config.isCorsSupportEnabled() && msg instanceof HttpResponse) { + if (config != null && config.isCorsSupportEnabled() && msg instanceof HttpResponse) { final HttpResponse response = (HttpResponse) msg; if (setOrigin(response)) { setAllowCredentials(response); diff --git a/common/src/main/java/io/netty/util/internal/ObjectUtil.java b/common/src/main/java/io/netty/util/internal/ObjectUtil.java index 28c3729fb9c..cbac561f32f 100644 --- a/common/src/main/java/io/netty/util/internal/ObjectUtil.java +++ b/common/src/main/java/io/netty/util/internal/ObjectUtil.java @@ -14,6 +14,8 @@ */ package io.netty.util.internal; +import java.util.Collection; + /** * A grab-bag of useful utility methods. */ @@ -88,6 +90,17 @@ public static <T> T[] checkNonEmpty(T[] array, String name) { return array; } + /** + * Checks that the given argument is neither null nor empty. + * If it is, throws {@link NullPointerException} or {@link IllegalArgumentException}. + * Otherwise, returns the argument. + */ + public static <T extends Collection<?>> T checkNonEmpty(T collection, String name) { + checkNotNull(collection, name); + checkPositive(collection.size(), name + ".size"); + return collection; + } + /** * Resolves a possibly null Integer to a primitive int, using a default value. * @param wrapper the wrapper
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java index f3fe97efd01..884c368796b 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/cors/CorsHandlerTest.java @@ -26,41 +26,26 @@ import io.netty.handler.codec.http.HttpUtil; import io.netty.util.AsciiString; import io.netty.util.ReferenceCountUtil; +import org.hamcrest.core.IsEqual; import org.junit.Test; import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.concurrent.Callable; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; -import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD; -import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; -import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; -import static io.netty.handler.codec.http.HttpHeaderNames.DATE; -import static io.netty.handler.codec.http.HttpHeaderNames.ORIGIN; -import static io.netty.handler.codec.http.HttpHeaderNames.VARY; -import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE; +import static io.netty.handler.codec.http.HttpHeaderNames.*; import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE; +import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE; import static io.netty.handler.codec.http.HttpHeadersTestUtils.of; -import static io.netty.handler.codec.http.HttpMethod.DELETE; -import static io.netty.handler.codec.http.HttpMethod.GET; -import static io.netty.handler.codec.http.HttpMethod.OPTIONS; +import static io.netty.handler.codec.http.HttpMethod.*; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -import static io.netty.handler.codec.http.cors.CorsConfigBuilder.forAnyOrigin; -import static io.netty.handler.codec.http.cors.CorsConfigBuilder.forOrigin; -import static io.netty.handler.codec.http.cors.CorsConfigBuilder.forOrigins; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; +import static io.netty.handler.codec.http.cors.CorsConfigBuilder.*; +import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; public class CorsHandlerTest { @@ -422,6 +407,46 @@ public void forbiddenShouldReleaseRequest() { assertThat(channel.finish(), is(false)); } + @Test + public void differentConfigsPerOrigin() { + String host1 = "http://host1:80"; + String host2 = "http://host2"; + CorsConfig rule1 = forOrigin(host1).allowedRequestMethods(HttpMethod.GET).build(); + CorsConfig rule2 = forOrigin(host2).allowedRequestMethods(HttpMethod.GET, HttpMethod.POST) + .allowCredentials().build(); + + List<CorsConfig> corsConfigs = Arrays.asList(rule1, rule2); + + final HttpResponse preFlightHost1 = preflightRequest(corsConfigs, host1, "", false); + assertThat(preFlightHost1.headers().get(ACCESS_CONTROL_ALLOW_METHODS), is("GET")); + assertThat(preFlightHost1.headers().getAsString(ACCESS_CONTROL_ALLOW_CREDENTIALS), is(nullValue())); + + final HttpResponse preFlightHost2 = preflightRequest(corsConfigs, host2, "", false); + assertValues(preFlightHost2, ACCESS_CONTROL_ALLOW_METHODS.toString(), "GET", "POST"); + assertThat(preFlightHost2.headers().getAsString(ACCESS_CONTROL_ALLOW_CREDENTIALS), IsEqual.equalTo("true")); + } + + @Test + public void specificConfigPrecedenceOverGeneric() { + String host1 = "http://host1"; + String host2 = "http://host2"; + + CorsConfig forHost1 = forOrigin(host1).allowedRequestMethods(HttpMethod.GET).maxAge(3600L).build(); + CorsConfig allowAll = forAnyOrigin().allowedRequestMethods(HttpMethod.POST, HttpMethod.GET, HttpMethod.OPTIONS) + .maxAge(1800).build(); + + List<CorsConfig> rules = Arrays.asList(forHost1, allowAll); + + final HttpResponse host1Response = preflightRequest(rules, host1, "", false); + assertThat(host1Response.headers().get(ACCESS_CONTROL_ALLOW_METHODS), is("GET")); + assertThat(host1Response.headers().getAsString(ACCESS_CONTROL_MAX_AGE), equalTo("3600")); + + final HttpResponse host2Response = preflightRequest(rules, host2, "", false); + assertValues(host2Response, ACCESS_CONTROL_ALLOW_METHODS.toString(), "POST", "GET", "OPTIONS"); + assertThat(host2Response.headers().getAsString(ACCESS_CONTROL_ALLOW_ORIGIN), equalTo("*")); + assertThat(host2Response.headers().getAsString(ACCESS_CONTROL_MAX_AGE), equalTo("1800")); + } + private static HttpResponse simpleRequest(final CorsConfig config, final String origin) { return simpleRequest(config, origin, null); } @@ -451,7 +476,14 @@ private static HttpResponse simpleRequest(final CorsConfig config, private static HttpResponse preflightRequest(final CorsConfig config, final String origin, final String requestHeaders) { - final EmbeddedChannel channel = new EmbeddedChannel(new CorsHandler(config)); + return preflightRequest(Collections.singletonList(config), origin, requestHeaders, config.isShortCircuit()); + } + + private static HttpResponse preflightRequest(final List<CorsConfig> configs, + final String origin, + final String requestHeaders, + final boolean isSHortCircuit) { + final EmbeddedChannel channel = new EmbeddedChannel(new CorsHandler(configs, isSHortCircuit)); assertThat(channel.writeInbound(optionsRequest(origin, requestHeaders, null)), is(false)); HttpResponse response = channel.readOutbound(); assertThat(channel.finish(), is(false));
train
val
"2018-03-20T15:59:08"
"2018-03-16T17:10:44Z"
gustavocoding
val
netty/netty/7255_7801
netty/netty
netty/netty/7255
netty/netty/7801
[ "timestamp(timedelta=3404.0, similarity=0.850000755448666)" ]
6e6cfa0604aa578b52ed5d72ac954f040fadffa3
ed0668384b393c3502c2136e3cc412a5c8c9056e
[ "Thank you for fast response. It will fix issue for non-autoread channels (original issue), but after looking at affected code I'm afraid that channels with `AUTO_READ` can be hurt with this wakeups.", "@khitrin so you are saying it is not fixed with the PR ?", "I've built netty with the PR and can confirm that original issue is fixed.\r\n\r\nBut I think we need further investigation of this case.\r\n\r\n1. For 4.1.16.Final (from Maven central) event spam begins immediately when upstream break the connection. Also I checked that setting `readPending` to `false` by debugger helps, so the PR clearly must fix the issue.\r\n\r\n2. For 4.1.17.Final-SNAPSHOT (with the PR) single event fired on next `.read()` call.\r\nIt is absolutely correct behaviour, but why 4.1.16.Final fires event without `.read()` and why it fixed by this PR?\r\nI will try to rebuild 4.1.16.Final on Mac and test it on Mac and Linux platforms. \r\n\r\nAlso similar issue may affect channels with auto read enabled and `readPending` disabling might be not enough here.\r\n", "also @Scottmitch ....", "Finally confirmed on Linux.", "@khitrin when you say confirmed... what do you mean ? Confirmed as this pr fix it or what ?", "@normanmaurer, I've checked against @khitrin's source with 4.1.16.Final where issue is present on Linux and with 4.1.17.Final-SNAPSHOT from your PR #7259 which behaves same as on MacOSX. So, PR fixes issue same way as on Mac.", "I'm still seeing this problem in 4.1.22.Final on Linux (Ubuntu 16.04, OpenJDK 1.8.0_151), which appears to have all the abovementioned fixes in place. I'm using the default NIO channel implementation, and am seeing thousands of these events fired when I shutdown the input.\r\n", "hmm interesting... @Scottmitch Can you have a look ?", "See https://github.com/netty/netty/pull/7801", "@khitrin how do you find the Suspicious code?" ]
[ "Replace `DefaultSocketChannelConfig` with `SocketChannelConfig`. After this its ready to be merged :)" ]
"2018-03-21T19:26:46Z"
[ "defect" ]
A lot of ChannelInputShutdownReadComplete events fired for NIO channel with ALLOW_HALF_CLOSURE
### Expected behavior Single `ChannelInputShutdownReadComplete` event will be fired for closed socket. ### Actual behavior `ChannelInputShutdownReadComplete` event fired on each NIO event loop run. `NioEventLoop` begin consuming a lot of CPU. ### Steps to reproduce Create upstream connection channel with enabled `ALLOW_HALF_CLOSURE` and disabled `AUTO_READ`, do a single HTTP keep-alive request and wait until connection being closed by remote server. ### Netty version 4.1.16.Final ### JVM version (e.g. `java -version`) Java(TM) SE Runtime Environment (build 1.8.0_131-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode) ### OS version (e.g. `uname -a`) Darwin 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64 macOS Sierra 10.12.6 Also confirmed on Linux. ### Suspicious code fragment from `io.netty.channel.nio.AbstractNioByteChannel::read` https://github.com/netty/netty/blob/f57d8f00e17a3cbd127aeb2b499c3f2787c002e4/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java#L124-L133 `readPending` not cleared when `allocHandle.lastBytesRead() <= 0`. Negative read bytes indicates socket closed state, but each consecutive selection of this socket key with `OP_READ` will succeed immediately (may be related to http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4531726). ### Fix proposal Call `removeReadOp()` on closed sockets.
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java", "transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java" ]
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java", "transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java", "transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java", "transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java" ]
[ "testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java" ]
diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java index 8d3dc5bbcbd..c1af9975cd2 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/AbstractEpollChannel.java @@ -33,6 +33,7 @@ import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.channel.socket.ChannelInputShutdownReadComplete; +import io.netty.channel.socket.SocketChannelConfig; import io.netty.channel.unix.FileDescriptor; import io.netty.channel.unix.Socket; import io.netty.channel.unix.UnixChannel; @@ -241,8 +242,8 @@ final boolean shouldBreakEpollInReady(ChannelConfig config) { } private static boolean isAllowHalfClosure(ChannelConfig config) { - return config instanceof EpollSocketChannelConfig && - ((EpollSocketChannelConfig) config).isAllowHalfClosure(); + return config instanceof SocketChannelConfig && + ((SocketChannelConfig) config).isAllowHalfClosure(); } final void clearEpollIn() { diff --git a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java index f10417ebe17..698e59c7f16 100644 --- a/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java +++ b/transport-native-kqueue/src/main/java/io/netty/channel/kqueue/AbstractKQueueChannel.java @@ -33,6 +33,7 @@ import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.channel.socket.ChannelInputShutdownReadComplete; +import io.netty.channel.socket.SocketChannelConfig; import io.netty.channel.unix.FileDescriptor; import io.netty.channel.unix.UnixChannel; import io.netty.util.ReferenceCountUtil; @@ -322,8 +323,8 @@ final boolean shouldBreakReadReady(ChannelConfig config) { } private static boolean isAllowHalfClosure(ChannelConfig config) { - return config instanceof KQueueSocketChannelConfig && - ((KQueueSocketChannelConfig) config).isAllowHalfClosure(); + return config instanceof SocketChannelConfig && + ((SocketChannelConfig) config).isAllowHalfClosure(); } final void clearReadFilter() { diff --git a/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java b/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java index ffa0d67d479..db87b100b0c 100644 --- a/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java +++ b/transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java @@ -21,7 +21,6 @@ import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelMetadata; -import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelPipeline; import io.netty.channel.FileRegion; @@ -29,6 +28,7 @@ import io.netty.channel.internal.ChannelUtils; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.channel.socket.ChannelInputShutdownReadComplete; +import io.netty.channel.socket.SocketChannelConfig; import io.netty.util.internal.StringUtil; import java.io.IOException; @@ -54,6 +54,7 @@ public void run() { ((AbstractNioUnsafe) unsafe()).flush0(); } }; + private boolean inputClosedSeenErrorOnRead; /** * Create a new instance @@ -84,17 +85,27 @@ public ChannelMetadata metadata() { return METADATA; } + final boolean shouldBreakReadReady(ChannelConfig config) { + return isInputShutdown0() && (inputClosedSeenErrorOnRead || !isAllowHalfClosure(config)); + } + + private static boolean isAllowHalfClosure(ChannelConfig config) { + return config instanceof SocketChannelConfig && + ((SocketChannelConfig) config).isAllowHalfClosure(); + } + protected class NioByteUnsafe extends AbstractNioUnsafe { private void closeOnRead(ChannelPipeline pipeline) { if (!isInputShutdown0()) { - if (Boolean.TRUE.equals(config().getOption(ChannelOption.ALLOW_HALF_CLOSURE))) { + if (isAllowHalfClosure(config())) { shutdownInput(); pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE); } else { close(voidPromise()); } } else { + inputClosedSeenErrorOnRead = true; pipeline.fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE); } } @@ -120,6 +131,10 @@ private void handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf, Thro @Override public final void read() { final ChannelConfig config = config(); + if (shouldBreakReadReady(config)) { + clearReadPending(); + return; + } final ChannelPipeline pipeline = pipeline(); final ByteBufAllocator allocator = config.getAllocator(); final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle(); diff --git a/transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java b/transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java index 477f39ac67b..6eda848f82e 100644 --- a/transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java +++ b/transport/src/main/java/io/netty/channel/oio/AbstractOioByteChannel.java @@ -27,6 +27,7 @@ import io.netty.channel.FileRegion; import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.socket.ChannelInputShutdownEvent; +import io.netty.channel.socket.ChannelInputShutdownReadComplete; import io.netty.util.internal.StringUtil; import java.io.IOException; @@ -73,6 +74,7 @@ private void closeOnRead(ChannelPipeline pipeline) { } else { unsafe().close(unsafe().voidPromise()); } + pipeline.fireUserEventTriggered(ChannelInputShutdownReadComplete.INSTANCE); } }
diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java index b5600d4252c..40b5e86ff73 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketHalfClosedTest.java @@ -40,10 +40,82 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class SocketHalfClosedTest extends AbstractSocketTest { + @Test(timeout = 10000) + public void testHalfClosureOnlyOneEventWhenAutoRead() throws Throwable { + run(); + } + + public void testHalfClosureOnlyOneEventWhenAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable { + Channel serverChannel = null; + try { + cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true) + .option(ChannelOption.AUTO_READ, true); + sb.childHandler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(ChannelHandlerContext ctx) { + ((DuplexChannel) ctx).shutdownOutput(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + ctx.close(); + } + }); + } + }); + + final AtomicInteger shutdownEventReceivedCounter = new AtomicInteger(); + final AtomicInteger shutdownReadCompleteEventReceivedCounter = new AtomicInteger(); + + cb.handler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { + + @Override + public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) { + if (evt == ChannelInputShutdownEvent.INSTANCE) { + shutdownEventReceivedCounter.incrementAndGet(); + } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) { + shutdownReadCompleteEventReceivedCounter.incrementAndGet(); + ctx.executor().schedule(new Runnable() { + @Override + public void run() { + ctx.close(); + } + }, 100, MILLISECONDS); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + ctx.close(); + } + }); + } + }); + + serverChannel = sb.bind().sync().channel(); + Channel clientChannel = cb.connect(serverChannel.localAddress()).sync().channel(); + clientChannel.closeFuture().await(); + assertEquals(1, shutdownEventReceivedCounter.get()); + assertEquals(1, shutdownReadCompleteEventReceivedCounter.get()); + } finally { + if (serverChannel != null) { + serverChannel.close().sync(); + } + } + } + @Test public void testAllDataReadAfterHalfClosure() throws Throwable { run();
train
val
"2018-03-20T15:59:08"
"2017-09-27T18:16:16Z"
khitrin
val
netty/netty/7795_7803
netty/netty
netty/netty/7795
netty/netty/7803
[ "keyword_pr_to_issue" ]
5ebee9426f05b0c9287bf8c0e27e9e37e1d96c66
cd4594d29244f7bea9d718e74ec4ecdcb6c62c13
[ "and does it sound good? :-)", "I'll start to work on this if there's no objection." ]
[ "javadocs please", "revert ?", "...that are...", "...that are...", "...that are...", "Added Javadocs for `DnsAddressDecoder`", "Oops! Reverted.", "Fixed all :-)", "can we use `NetUtil.IPV6_BYTE_COUNT` here instead of duplicating the definition?", "`gotResult` -> `containsExpectedResultType`?", "consider adding a comment to provide justification for `86400`.", "should this method live next to `protected void doResolveAll(String inetHost,...)` and do effectively the same thing? Differences:\r\n\r\n- There is some local host and IP checking up front before losing in local hosts file.\r\n- the cache is consulted first before doing a `new DnsAddressResolveContext(..).resolve(..)`.\r\n- `doResolveAll` is overridable to substitute another cache\r\n\r\nto pull off the cache items we may need to modify the cache API to lookup `DnsQuestion` instead of just raw hostname. Is there a technical reason why enhancing the cache would be problematic?", "nit: remove `throws Exception`", "should this be `!finalResult.isEmpty()`?", "consider adding a comment that if/when we cache then we would need to `ReferenceCountUtil.retain` the `DnsRecord` (and maybe the original `DnsQuestion`).", "`thing interesting` -> `expected/desired answers`?", "dropping the redirect may have undesired results if other behavior in this class changes, or DNS server is not as expected so consider adding a comment here. IIUC we are assuming the following behavior:\r\n\r\n- this DNS resolver will issue a query for each `A` and `AAAA` records if they are both supported.\r\n- it is assumed the DNS server will only provide redirects of the same type as the query, and therefore it is safe to drop redirects where types don't match. In addition if the DNS server responds with mismatching (or maybe all types) types it is desirable to filter the redirects to avoid multiple queries for the same redirect.", "is it possible to instead use the test DNS server that runs locally and verify results are as expected?", "They are private fields and highly unlikely to change, so I'd like to keep these as they are.", "Renamed to `containsExpectedResult`", "Added", "Initial cache API was designed to cache the complete DNS response, but it caused various issues with reference counting because it kept `DnsRawRecord`. We may be able to make this change once we implement all `DnsRecord` implementations for all known DNS record types. For now, we can't use cache for arbitrary record types.", "Fixed", "It never gives an empty list by contract. Let me update the Javadoc of this method.", "Added comment", "Fixed", "I actually checked if the result contains a valid MX record, just like `queryMx()` does. The log messages are for debugging. `queryMx()` logs the same. And the test case uses the test DNS server rather than a public DNS server.", "Actually, it was a bug. This change has to be reverted.", "doh ... missed that this is going against the local dns server. validating the mx record contents to ensure decoding is correct may be challenging due to the random nature of DnsTestServer I guess.", "I still think there is value in consolidating the definitions, but not a deal breaker." ]
"2018-03-22T14:01:59Z"
[ "feature" ]
Expose DnsNameResolverContext (or something equivalent to it) to users
A user may want to reuse the logic related with search list enumeration, retries and error handling in his or her resolver implementations. For example, a user could extend or customize `DnsNameResolverContext` to implement DNS-based service discovery that retrieves [SRV records](https://en.wikipedia.org/wiki/SRV_record), while respecting the global resolver configuration (`/etc/resolv.conf`). Currently, the user would have to re-implement search list enumeration, retries and error handling by his or her own. Let me take a stab of this if it sounds good.
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressDecoder.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolveContext.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsRecordResolveContext.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java" ]
[ "resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java" ]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressDecoder.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressDecoder.java new file mode 100644 index 00000000000..3dfb56ae8cc --- /dev/null +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressDecoder.java @@ -0,0 +1,67 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.resolver.dns; + +import java.net.IDN; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufHolder; +import io.netty.handler.codec.dns.DnsRawRecord; +import io.netty.handler.codec.dns.DnsRecord; + +/** + * Decodes an {@link InetAddress} from an A or AAAA {@link DnsRawRecord}. + */ +final class DnsAddressDecoder { + + private static final int INADDRSZ4 = 4; + private static final int INADDRSZ6 = 16; + + /** + * Decodes an {@link InetAddress} from an A or AAAA {@link DnsRawRecord}. + * + * @param record the {@link DnsRecord}, most likely a {@link DnsRawRecord} + * @param name the host name of the decoded address + * @param decodeIdn whether to convert {@code name} to a unicode host name + * + * @return the {@link InetAddress}, or {@code null} if {@code record} is not a {@link DnsRawRecord} or + * its content is malformed + */ + static InetAddress decodeAddress(DnsRecord record, String name, boolean decodeIdn) { + if (!(record instanceof DnsRawRecord)) { + return null; + } + final ByteBuf content = ((ByteBufHolder) record).content(); + final int contentLen = content.readableBytes(); + if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) { + return null; + } + + final byte[] addrBytes = new byte[contentLen]; + content.getBytes(content.readerIndex(), addrBytes); + + try { + return InetAddress.getByAddress(decodeIdn ? IDN.toUnicode(name) : name, addrBytes); + } catch (UnknownHostException e) { + // Should never reach here. + throw new Error(e); + } + } + + private DnsAddressDecoder() { } +} diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolveContext.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolveContext.java new file mode 100644 index 00000000000..95dcb136ed6 --- /dev/null +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolveContext.java @@ -0,0 +1,74 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.resolver.dns; + +import static io.netty.resolver.dns.DnsAddressDecoder.decodeAddress; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; + +import io.netty.channel.EventLoop; +import io.netty.handler.codec.dns.DnsRecord; +import io.netty.handler.codec.dns.DnsRecordType; + +final class DnsAddressResolveContext extends DnsResolveContext<InetAddress> { + + private final DnsCache resolveCache; + + DnsAddressResolveContext(DnsNameResolver parent, String hostname, DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs, DnsCache resolveCache) { + super(parent, hostname, DnsRecord.CLASS_IN, parent.resolveRecordTypes(), additionals, nameServerAddrs); + this.resolveCache = resolveCache; + } + + @Override + DnsResolveContext<InetAddress> newResolverContext(DnsNameResolver parent, String hostname, + int dnsClass, DnsRecordType[] expectedTypes, + DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs) { + return new DnsAddressResolveContext(parent, hostname, additionals, nameServerAddrs, resolveCache); + } + + @Override + InetAddress convertRecord(DnsRecord record, String hostname, DnsRecord[] additionals, EventLoop eventLoop) { + return decodeAddress(record, hostname, parent.isDecodeIdn()); + } + + @Override + boolean containsExpectedResult(List<InetAddress> finalResult) { + final int size = finalResult.size(); + final Class<? extends InetAddress> inetAddressType = parent.preferredAddressType().addressType(); + for (int i = 0; i < size; i++) { + InetAddress address = finalResult.get(i); + if (inetAddressType.isInstance(address)) { + return true; + } + } + return false; + } + + @Override + void cache(String hostname, DnsRecord[] additionals, + DnsRecord result, InetAddress convertedResult) { + resolveCache.cache(hostname, additionals, convertedResult, result.timeToLive(), parent.ch.eventLoop()); + } + + @Override + void cache(String hostname, DnsRecord[] additionals, UnknownHostException cause) { + resolveCache.cache(hostname, additionals, cause, parent.ch.eventLoop()); + } +} diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java index eaa714026d2..5bd7baad259 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java @@ -16,6 +16,8 @@ package io.netty.resolver.dns; import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; import io.netty.channel.AddressedEnvelope; import io.netty.channel.Channel; import io.netty.channel.ChannelFactory; @@ -33,11 +35,13 @@ import io.netty.handler.codec.dns.DatagramDnsQueryEncoder; import io.netty.handler.codec.dns.DatagramDnsResponse; import io.netty.handler.codec.dns.DatagramDnsResponseDecoder; +import io.netty.handler.codec.dns.DefaultDnsRawRecord; import io.netty.handler.codec.dns.DnsQuestion; import io.netty.handler.codec.dns.DnsRawRecord; import io.netty.handler.codec.dns.DnsRecord; import io.netty.handler.codec.dns.DnsRecordType; import io.netty.handler.codec.dns.DnsResponse; +import io.netty.resolver.HostsFileEntries; import io.netty.resolver.HostsFileEntriesResolver; import io.netty.resolver.InetNameResolver; import io.netty.resolver.ResolvedAddressTypes; @@ -45,6 +49,7 @@ import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.Promise; import io.netty.util.internal.EmptyArrays; import io.netty.util.internal.PlatformDependent; @@ -55,6 +60,8 @@ import java.lang.reflect.Method; import java.net.IDN; +import java.net.Inet4Address; +import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; @@ -527,6 +534,96 @@ protected void doResolve(String inetHost, Promise<InetAddress> promise) throws E doResolve(inetHost, EMPTY_ADDITIONALS, promise, resolveCache); } + /** + * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike + * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers. + * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured + * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the + * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned. + * + * @param question the question + * + * @return the list of the {@link DnsRecord}s as the result of the resolution + */ + public final Future<List<DnsRecord>> resolveAll(DnsQuestion question) { + return resolveAll(question, EMPTY_ADDITIONALS, executor().<List<DnsRecord>>newPromise()); + } + + /** + * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike + * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers. + * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured + * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the + * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned. + * + * @param question the question + * @param additionals additional records ({@code OPT}) + * + * @return the list of the {@link DnsRecord}s as the result of the resolution + */ + public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals) { + return resolveAll(question, additionals, executor().<List<DnsRecord>>newPromise()); + } + + /** + * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike + * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers. + * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured + * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the + * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned. + * + * @param question the question + * @param additionals additional records ({@code OPT}) + * @param promise the {@link Promise} which will be fulfilled when the resolution is finished + * + * @return the list of the {@link DnsRecord}s as the result of the resolution + */ + public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals, + Promise<List<DnsRecord>> promise) { + final DnsRecord[] additionalsArray = toArray(additionals, true); + return resolveAll(question, additionalsArray, promise); + } + + private Future<List<DnsRecord>> resolveAll(DnsQuestion question, DnsRecord[] additionals, + Promise<List<DnsRecord>> promise) { + checkNotNull(question, "question"); + checkNotNull(promise, "promise"); + + // Respect /etc/hosts as well if the record type is A or AAAA. + final DnsRecordType type = question.type(); + final String hostname = question.name(); + + if (type == DnsRecordType.A || type == DnsRecordType.AAAA) { + final InetAddress hostsFileEntry = resolveHostsFileEntry(hostname); + if (hostsFileEntry != null) { + ByteBuf content = null; + if (hostsFileEntry instanceof Inet4Address) { + if (type == DnsRecordType.A) { + content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress()); + } + } else if (hostsFileEntry instanceof Inet6Address) { + if (type == DnsRecordType.AAAA) { + content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress()); + } + } + + if (content != null) { + // Our current implementation does not support reloading the hosts file, + // so use a fairly large TTL (1 day, i.e. 86400 seconds). + trySuccess(promise, Collections.<DnsRecord>singletonList( + new DefaultDnsRawRecord(hostname, type, 86400, content))); + return promise; + } + } + } + + // It was not A/AAAA question or there was no entry in /etc/hosts. + final DnsServerAddressStream nameServerAddrs = + dnsServerAddressStreamProvider.nameServerAddressStream(hostname); + new DnsRecordResolveContext(this, question, additionals, nameServerAddrs).resolve(promise); + return promise; + } + private static DnsRecord[] toArray(Iterable<DnsRecord> additionals, boolean validateType) { checkNotNull(additionals, "additionals"); if (additionals instanceof Collection) { @@ -624,7 +721,7 @@ private boolean doResolveCached(String hostname, } } - private static <T> void trySuccess(Promise<T> promise, T result) { + static <T> void trySuccess(Promise<T> promise, T result) { if (!promise.trySuccess(result)) { logger.warn("Failed to notify success ({}) to a promise: {}", result, promise); } @@ -638,40 +735,20 @@ private static void tryFailure(Promise<?> promise, Throwable cause) { private void doResolveUncached(String hostname, DnsRecord[] additionals, - Promise<InetAddress> promise, + final Promise<InetAddress> promise, DnsCache resolveCache) { - new SingleResolverContext(this, hostname, additionals, resolveCache, - dnsServerAddressStreamProvider.nameServerAddressStream(hostname)).resolve(promise); - } - - static final class SingleResolverContext extends DnsNameResolverContext<InetAddress> { - SingleResolverContext(DnsNameResolver parent, String hostname, - DnsRecord[] additionals, DnsCache resolveCache, DnsServerAddressStream nameServerAddrs) { - super(parent, hostname, additionals, resolveCache, nameServerAddrs); - } - - @Override - DnsNameResolverContext<InetAddress> newResolverContext(DnsNameResolver parent, String hostname, - DnsRecord[] additionals, DnsCache resolveCache, - DnsServerAddressStream nameServerAddrs) { - return new SingleResolverContext(parent, hostname, additionals, resolveCache, nameServerAddrs); - } - - @Override - boolean finishResolve( - Class<? extends InetAddress> addressType, List<DnsCacheEntry> resolvedEntries, - Promise<InetAddress> promise) { - - final int numEntries = resolvedEntries.size(); - for (int i = 0; i < numEntries; i++) { - final InetAddress a = resolvedEntries.get(i).address(); - if (addressType.isInstance(a)) { - trySuccess(promise, a); - return true; + final Promise<List<InetAddress>> allPromise = executor().newPromise(); + doResolveAllUncached(hostname, additionals, allPromise, resolveCache); + allPromise.addListener(new FutureListener<List<InetAddress>>() { + @Override + public void operationComplete(Future<List<InetAddress>> future) { + if (future.isSuccess()) { + trySuccess(promise, future.getNow().get(0)); + } else { + tryFailure(promise, future.cause()); } } - return false; - } + }); } @Override @@ -747,50 +824,13 @@ private boolean doResolveAllCached(String hostname, } } - static final class ListResolverContext extends DnsNameResolverContext<List<InetAddress>> { - ListResolverContext(DnsNameResolver parent, String hostname, - DnsRecord[] additionals, DnsCache resolveCache, DnsServerAddressStream nameServerAddrs) { - super(parent, hostname, additionals, resolveCache, nameServerAddrs); - } - - @Override - DnsNameResolverContext<List<InetAddress>> newResolverContext( - DnsNameResolver parent, String hostname, DnsRecord[] additionals, DnsCache resolveCache, - DnsServerAddressStream nameServerAddrs) { - return new ListResolverContext(parent, hostname, additionals, resolveCache, nameServerAddrs); - } - - @Override - boolean finishResolve( - Class<? extends InetAddress> addressType, List<DnsCacheEntry> resolvedEntries, - Promise<List<InetAddress>> promise) { - - List<InetAddress> result = null; - final int numEntries = resolvedEntries.size(); - for (int i = 0; i < numEntries; i++) { - final InetAddress a = resolvedEntries.get(i).address(); - if (addressType.isInstance(a)) { - if (result == null) { - result = new ArrayList<InetAddress>(numEntries); - } - result.add(a); - } - } - - if (result != null) { - promise.trySuccess(result); - return true; - } - return false; - } - } - private void doResolveAllUncached(String hostname, DnsRecord[] additionals, Promise<List<InetAddress>> promise, DnsCache resolveCache) { - new ListResolverContext(this, hostname, additionals, resolveCache, - dnsServerAddressStreamProvider.nameServerAddressStream(hostname)).resolve(promise); + final DnsServerAddressStream nameServerAddrs = + dnsServerAddressStreamProvider.nameServerAddressStream(hostname); + new DnsAddressResolveContext(this, hostname, additionals, nameServerAddrs, resolveCache).resolve(promise); } private static String hostname(String inetHost) { diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsRecordResolveContext.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsRecordResolveContext.java new file mode 100644 index 00000000000..34b548ba623 --- /dev/null +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsRecordResolveContext.java @@ -0,0 +1,75 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.resolver.dns; + +import static io.netty.resolver.dns.DnsAddressDecoder.decodeAddress; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; + +import io.netty.channel.EventLoop; +import io.netty.handler.codec.dns.DnsQuestion; +import io.netty.handler.codec.dns.DnsRecord; +import io.netty.handler.codec.dns.DnsRecordType; +import io.netty.util.ReferenceCountUtil; + +final class DnsRecordResolveContext extends DnsResolveContext<DnsRecord> { + + DnsRecordResolveContext(DnsNameResolver parent, DnsQuestion question, DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs) { + this(parent, question.name(), question.dnsClass(), + new DnsRecordType[] { question.type() }, + additionals, nameServerAddrs); + } + + private DnsRecordResolveContext(DnsNameResolver parent, String hostname, + int dnsClass, DnsRecordType[] expectedTypes, + DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs) { + super(parent, hostname, dnsClass, expectedTypes, additionals, nameServerAddrs); + } + + @Override + DnsResolveContext<DnsRecord> newResolverContext(DnsNameResolver parent, String hostname, + int dnsClass, DnsRecordType[] expectedTypes, + DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs) { + return new DnsRecordResolveContext(parent, hostname, dnsClass, expectedTypes, additionals, nameServerAddrs); + } + + @Override + DnsRecord convertRecord(DnsRecord record, String hostname, DnsRecord[] additionals, EventLoop eventLoop) { + return ReferenceCountUtil.retain(record); + } + + @Override + boolean containsExpectedResult(List<DnsRecord> finalResult) { + return true; + } + + @Override + void cache(String hostname, DnsRecord[] additionals, DnsRecord result, DnsRecord convertedResult) { + // Do not cache. + // XXX: When we implement cache, we would need to retain the reference count of the result record. + } + + @Override + void cache(String hostname, DnsRecord[] additionals, UnknownHostException cause) { + // Do not cache. + // XXX: When we implement cache, we would need to retain the reference count of the result record. + } +} diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java similarity index 82% rename from resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java rename to resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java index 2eea34536ee..8d7c53a8243 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java @@ -20,7 +20,7 @@ import io.netty.buffer.ByteBufHolder; import io.netty.channel.AddressedEnvelope; import io.netty.channel.ChannelPromise; -import io.netty.channel.socket.InternetProtocolFamily; +import io.netty.channel.EventLoop; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.dns.DefaultDnsQuestion; import io.netty.handler.codec.dns.DefaultDnsRecordDecoder; @@ -40,7 +40,6 @@ import io.netty.util.internal.StringUtil; import io.netty.util.internal.ThrowableUtil; -import java.net.IDN; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; @@ -54,13 +53,12 @@ import java.util.Map; import java.util.Set; +import static io.netty.resolver.dns.DnsAddressDecoder.decodeAddress; +import static io.netty.resolver.dns.DnsNameResolver.trySuccess; import static java.lang.Math.min; import static java.util.Collections.unmodifiableList; -abstract class DnsNameResolverContext<T> { - - private static final int INADDRSZ4 = 4; - private static final int INADDRSZ6 = 16; +abstract class DnsResolveContext<T> { private static final FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>> RELEASE_RESPONSE = new FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>() { @@ -73,58 +71,90 @@ public void operationComplete(Future<AddressedEnvelope<DnsResponse, InetSocketAd }; private static final RuntimeException NXDOMAIN_QUERY_FAILED_EXCEPTION = ThrowableUtil.unknownStackTrace( new RuntimeException("No answer found and NXDOMAIN response code returned"), - DnsNameResolverContext.class, + DnsResolveContext.class, "onResponse(..)"); private static final RuntimeException CNAME_NOT_FOUND_QUERY_FAILED_EXCEPTION = ThrowableUtil.unknownStackTrace( new RuntimeException("No matching CNAME record found"), - DnsNameResolverContext.class, + DnsResolveContext.class, "onResponseCNAME(..)"); private static final RuntimeException NO_MATCHING_RECORD_QUERY_FAILED_EXCEPTION = ThrowableUtil.unknownStackTrace( new RuntimeException("No matching record type found"), - DnsNameResolverContext.class, + DnsResolveContext.class, "onResponseAorAAAA(..)"); private static final RuntimeException UNRECOGNIZED_TYPE_QUERY_FAILED_EXCEPTION = ThrowableUtil.unknownStackTrace( new RuntimeException("Response type was unrecognized"), - DnsNameResolverContext.class, + DnsResolveContext.class, "onResponse(..)"); private static final RuntimeException NAME_SERVERS_EXHAUSTED_EXCEPTION = ThrowableUtil.unknownStackTrace( new RuntimeException("No name servers returned an answer"), - DnsNameResolverContext.class, + DnsResolveContext.class, "tryToFinishResolve(..)"); - private final DnsNameResolver parent; + final DnsNameResolver parent; private final DnsServerAddressStream nameServerAddrs; private final String hostname; - private final DnsCache resolveCache; + private final int dnsClass; + private final DnsRecordType[] expectedTypes; private final int maxAllowedQueries; - private final InternetProtocolFamily[] resolvedInternetProtocolFamilies; private final DnsRecord[] additionals; private final Set<Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> queriesInProgress = Collections.newSetFromMap( new IdentityHashMap<Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>, Boolean>()); - private List<DnsCacheEntry> resolvedEntries; + private List<T> finalResult; private int allowedQueries; private boolean triedCNAME; - DnsNameResolverContext(DnsNameResolver parent, - String hostname, - DnsRecord[] additionals, - DnsCache resolveCache, - DnsServerAddressStream nameServerAddrs) { + DnsResolveContext(DnsNameResolver parent, + String hostname, int dnsClass, DnsRecordType[] expectedTypes, + DnsRecord[] additionals, DnsServerAddressStream nameServerAddrs) { + + assert expectedTypes.length > 0; + this.parent = parent; this.hostname = hostname; + this.dnsClass = dnsClass; + this.expectedTypes = expectedTypes; this.additionals = additionals; - this.resolveCache = resolveCache; this.nameServerAddrs = ObjectUtil.checkNotNull(nameServerAddrs, "nameServerAddrs"); maxAllowedQueries = parent.maxQueriesPerResolve(); - resolvedInternetProtocolFamilies = parent.resolvedInternetProtocolFamiliesUnsafe(); allowedQueries = maxAllowedQueries; } - void resolve(final Promise<T> promise) { + /** + * Creates a new context with the given parameters. + */ + abstract DnsResolveContext<T> newResolverContext(DnsNameResolver parent, String hostname, + int dnsClass, DnsRecordType[] expectedTypes, + DnsRecord[] additionals, + DnsServerAddressStream nameServerAddrs); + + /** + * Converts the given {@link DnsRecord} into {@code T}. + */ + abstract T convertRecord(DnsRecord record, String hostname, DnsRecord[] additionals, EventLoop eventLoop); + + /** + * Returns {@code true} if the given list contains any expected records. {@code finalResult} always contains + * at least one element. + */ + abstract boolean containsExpectedResult(List<T> finalResult); + + /** + * Caches a successful resolution. + */ + abstract void cache(String hostname, DnsRecord[] additionals, + DnsRecord result, T convertedResult); + + /** + * Caches a failed resolution. + */ + abstract void cache(String hostname, DnsRecord[] additionals, + UnknownHostException cause); + + void resolve(final Promise<List<T>> promise) { final String[] searchDomains = parent.searchDomains(); if (searchDomains.length == 0 || parent.ndots() == 0 || StringUtil.endsWith(hostname, '.')) { internalResolve(promise); @@ -133,10 +163,10 @@ void resolve(final Promise<T> promise) { final String initialHostname = startWithoutSearchDomain ? hostname : hostname + '.' + searchDomains[0]; final int initialSearchDomainIdx = startWithoutSearchDomain ? 0 : 1; - doSearchDomainQuery(initialHostname, new FutureListener<T>() { + doSearchDomainQuery(initialHostname, new FutureListener<List<T>>() { private int searchDomainIdx = initialSearchDomainIdx; @Override - public void operationComplete(Future<T> future) throws Exception { + public void operationComplete(Future<List<T>> future) throws Exception { Throwable cause = future.cause(); if (cause == null) { promise.trySuccess(future.getNow()); @@ -182,26 +212,24 @@ public Throwable fillInStackTrace() { } } - private void doSearchDomainQuery(String hostname, FutureListener<T> listener) { - DnsNameResolverContext<T> nextContext = newResolverContext(parent, hostname, additionals, resolveCache, - nameServerAddrs); - Promise<T> nextPromise = parent.executor().newPromise(); + private void doSearchDomainQuery(String hostname, FutureListener<List<T>> listener) { + DnsResolveContext<T> nextContext = newResolverContext(parent, hostname, dnsClass, expectedTypes, + additionals, nameServerAddrs); + Promise<List<T>> nextPromise = parent.executor().newPromise(); nextContext.internalResolve(nextPromise); nextPromise.addListener(listener); } - private void internalResolve(Promise<T> promise) { + private void internalResolve(Promise<List<T>> promise) { DnsServerAddressStream nameServerAddressStream = getNameServers(hostname); - DnsRecordType[] recordTypes = parent.resolveRecordTypes(); - assert recordTypes.length > 0; - final int end = recordTypes.length - 1; + final int end = expectedTypes.length - 1; for (int i = 0; i < end; ++i) { - if (!query(hostname, recordTypes[i], nameServerAddressStream.duplicate(), promise, null)) { + if (!query(hostname, expectedTypes[i], nameServerAddressStream.duplicate(), promise, null)) { return; } } - query(hostname, recordTypes[end], nameServerAddressStream, promise, null); + query(hostname, expectedTypes[end], nameServerAddressStream, promise, null); } /** @@ -291,7 +319,7 @@ public void remove() { private void query(final DnsServerAddressStream nameServerAddrStream, final int nameServerAddrStreamIndex, final DnsQuestion question, - final Promise<T> promise, Throwable cause) { + final Promise<List<T>> promise, Throwable cause) { query(nameServerAddrStream, nameServerAddrStreamIndex, question, parent.dnsQueryLifecycleObserverFactory().newDnsQueryLifecycleObserver(question), promise, cause); } @@ -300,7 +328,7 @@ private void query(final DnsServerAddressStream nameServerAddrStream, final int nameServerAddrStreamIndex, final DnsQuestion question, final DnsQueryLifecycleObserver queryLifecycleObserver, - final Promise<T> promise, + final Promise<List<T>> promise, final Throwable cause) { if (nameServerAddrStreamIndex >= nameServerAddrStream.size() || allowedQueries == 0 || promise.isCancelled()) { tryToFinishResolve(nameServerAddrStream, nameServerAddrStreamIndex, question, queryLifecycleObserver, @@ -359,7 +387,7 @@ public void operationComplete(Future<AddressedEnvelope<DnsResponse, InetSocketAd void onResponse(final DnsServerAddressStream nameServerAddrStream, final int nameServerAddrStreamIndex, final DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope, final DnsQueryLifecycleObserver queryLifecycleObserver, - Promise<T> promise) { + Promise<List<T>> promise) { try { final DnsResponse res = envelope.content(); final DnsResponseCode code = res.code(); @@ -370,13 +398,19 @@ void onResponse(final DnsServerAddressStream nameServerAddrStream, final int nam } final DnsRecordType type = question.type(); - if (type == DnsRecordType.A || type == DnsRecordType.AAAA) { - onResponseAorAAAA(type, question, envelope, queryLifecycleObserver, promise); - } else if (type == DnsRecordType.CNAME) { + if (type == DnsRecordType.CNAME) { onResponseCNAME(question, envelope, queryLifecycleObserver, promise); - } else { - queryLifecycleObserver.queryFailed(UNRECOGNIZED_TYPE_QUERY_FAILED_EXCEPTION); + return; + } + + for (DnsRecordType expectedType : expectedTypes) { + if (type == expectedType) { + onExpectedResponse(question, envelope, queryLifecycleObserver, promise); + return; + } } + + queryLifecycleObserver.queryFailed(UNRECOGNIZED_TYPE_QUERY_FAILED_EXCEPTION); return; } @@ -397,7 +431,7 @@ void onResponse(final DnsServerAddressStream nameServerAddrStream, final int nam */ private boolean handleRedirect( DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope, - final DnsQueryLifecycleObserver queryLifecycleObserver, Promise<T> promise) { + final DnsQueryLifecycleObserver queryLifecycleObserver, Promise<List<T>> promise) { final DnsResponse res = envelope.content(); // Check if we have answers, if not this may be an non authority NS and so redirects must be handled. @@ -417,15 +451,14 @@ private boolean handleRedirect( } final String recordName = r.name(); - AuthoritativeNameServer authoritativeNameServer = - serverNames.remove(recordName); + final AuthoritativeNameServer authoritativeNameServer = serverNames.remove(recordName); if (authoritativeNameServer == null) { // Not a server we are interested in. continue; } - InetAddress resolved = parseAddress(r, recordName); + InetAddress resolved = decodeAddress(r, recordName, parent.isDecodeIdn()); if (resolved == null) { // Could not parse it, move to the next. continue; @@ -462,10 +495,9 @@ private static AuthoritativeNameServerList extractAuthoritativeNameServers(Strin return serverNames; } - private void onResponseAorAAAA( - DnsRecordType qType, DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope, - final DnsQueryLifecycleObserver queryLifecycleObserver, - Promise<T> promise) { + private void onExpectedResponse( + DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope, + final DnsQueryLifecycleObserver queryLifecycleObserver, Promise<List<T>> promise) { // We often get a bunch of CNAMES as well when we asked for A/AAAA. final DnsResponse response = envelope.content(); @@ -476,7 +508,15 @@ private void onResponseAorAAAA( for (int i = 0; i < answerCount; i ++) { final DnsRecord r = response.recordAt(DnsSection.ANSWER, i); final DnsRecordType type = r.type(); - if (type != DnsRecordType.A && type != DnsRecordType.AAAA) { + boolean matches = false; + for (DnsRecordType expectedType : expectedTypes) { + if (type == expectedType) { + matches = true; + break; + } + } + + if (!matches) { continue; } @@ -499,17 +539,17 @@ private void onResponseAorAAAA( } } - InetAddress resolved = parseAddress(r, hostname); - if (resolved == null) { + final T converted = convertRecord(r, hostname, additionals, parent.ch.eventLoop()); + if (converted == null) { continue; } - if (resolvedEntries == null) { - resolvedEntries = new ArrayList<DnsCacheEntry>(8); + if (finalResult == null) { + finalResult = new ArrayList<T>(8); } + finalResult.add(converted); - resolvedEntries.add( - resolveCache.cache(hostname, additionals, resolved, r.timeToLive(), parent.ch.eventLoop())); + cache(hostname, additionals, r, converted); found = true; // Note that we do not break from the loop here, so we decode/cache all A/AAAA records. @@ -523,47 +563,23 @@ private void onResponseAorAAAA( if (cnames.isEmpty()) { queryLifecycleObserver.queryFailed(NO_MATCHING_RECORD_QUERY_FAILED_EXCEPTION); } else { - // We asked for A/AAAA but we got only CNAME. - onResponseCNAME(question, envelope, cnames, queryLifecycleObserver, promise); - } - } - - private InetAddress parseAddress(DnsRecord r, String name) { - if (!(r instanceof DnsRawRecord)) { - return null; - } - final ByteBuf content = ((ByteBufHolder) r).content(); - final int contentLen = content.readableBytes(); - if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) { - return null; - } - - final byte[] addrBytes = new byte[contentLen]; - content.getBytes(content.readerIndex(), addrBytes); - - try { - return InetAddress.getByAddress( - parent.isDecodeIdn() ? IDN.toUnicode(name) : name, addrBytes); - } catch (UnknownHostException e) { - // Should never reach here. - throw new Error(e); + // We got only CNAME, not one of expectedTypes. + onResponseCNAME(question, cnames, queryLifecycleObserver, promise); } } private void onResponseCNAME(DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope, - final DnsQueryLifecycleObserver queryLifecycleObserver, - Promise<T> promise) { - onResponseCNAME(question, envelope, buildAliasMap(envelope.content()), queryLifecycleObserver, promise); + final DnsQueryLifecycleObserver queryLifecycleObserver, Promise<List<T>> promise) { + onResponseCNAME(question, buildAliasMap(envelope.content()), queryLifecycleObserver, promise); } private void onResponseCNAME( - DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> response, - Map<String, String> cnames, final DnsQueryLifecycleObserver queryLifecycleObserver, - Promise<T> promise) { + DnsQuestion question, Map<String, String> cnames, + final DnsQueryLifecycleObserver queryLifecycleObserver, + Promise<List<T>> promise) { // Resolve the host name in the question into the real host name. - final String name = question.name().toLowerCase(Locale.US); - String resolved = name; + String resolved = question.name().toLowerCase(Locale.US); boolean found = false; while (!cnames.isEmpty()) { // Do not attempt to call Map.remove() when the Map is empty // because it can be Collections.emptyMap() @@ -618,24 +634,24 @@ void tryToFinishResolve(final DnsServerAddressStream nameServerAddrStream, final int nameServerAddrStreamIndex, final DnsQuestion question, final DnsQueryLifecycleObserver queryLifecycleObserver, - final Promise<T> promise, + final Promise<List<T>> promise, final Throwable cause) { // There are no queries left to try. if (!queriesInProgress.isEmpty()) { queryLifecycleObserver.queryCancelled(allowedQueries); // There are still some queries we did not receive responses for. - if (gotPreferredAddress()) { - // But it's OK to finish the resolution process if we got a resolved address of the preferred type. + if (finalResult != null && containsExpectedResult(finalResult)) { + // But it's OK to finish the resolution process if we got something expected. finishResolve(promise, cause); } - // We did not get any resolved address of the preferred type, so we can't finish the resolution process. + // We did not get an expected result yet, so we can't finish the resolution process. return; } // There are no queries left to try. - if (resolvedEntries == null) { + if (finalResult == null) { if (nameServerAddrStreamIndex < nameServerAddrStream.size()) { if (queryLifecycleObserver == NoopDnsQueryLifecycleObserver.INSTANCE) { // If the queryLifecycleObserver has already been terminated we should create a new one for this @@ -650,11 +666,11 @@ void tryToFinishResolve(final DnsServerAddressStream nameServerAddrStream, queryLifecycleObserver.queryFailed(NAME_SERVERS_EXHAUSTED_EXCEPTION); - // .. and we could not find any A/AAAA records. + // .. and we could not find any expected records. // If cause != null we know this was caused by a timeout / cancel / transport exception. In this case we - // won't try to resolve the CNAME as we only should do this if we could not get the A/AAAA records because - // these not exists and the DNS server did probably signal it. + // won't try to resolve the CNAME as we only should do this if we could not get the expected records + // because they do not exist and the DNS server did probably signal it. if (cause == null && !triedCNAME) { // As the last resort, try to query CNAME, just in case the name server has it. triedCNAME = true; @@ -666,27 +682,11 @@ void tryToFinishResolve(final DnsServerAddressStream nameServerAddrStream, queryLifecycleObserver.queryCancelled(allowedQueries); } - // We have at least one resolved address or tried CNAME as the last resort.. + // We have at least one resolved record or tried CNAME as the last resort.. finishResolve(promise, cause); } - private boolean gotPreferredAddress() { - if (resolvedEntries == null) { - return false; - } - - final int size = resolvedEntries.size(); - final Class<? extends InetAddress> inetAddressType = parent.preferredAddressType().addressType(); - for (int i = 0; i < size; i++) { - InetAddress address = resolvedEntries.get(i).address(); - if (inetAddressType.isInstance(address)) { - return true; - } - } - return false; - } - - private void finishResolve(Promise<T> promise, Throwable cause) { + private void finishResolve(Promise<List<T>> promise, Throwable cause) { if (!queriesInProgress.isEmpty()) { // If there are queries in progress, we should cancel it because we already finished the resolution. for (Iterator<Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> i = queriesInProgress.iterator(); @@ -700,13 +700,10 @@ private void finishResolve(Promise<T> promise, Throwable cause) { } } - if (resolvedEntries != null) { - // Found at least one resolved address. - for (InternetProtocolFamily f: resolvedInternetProtocolFamilies) { - if (finishResolve(f.addressType(), resolvedEntries, promise)) { - return; - } - } + if (finalResult != null) { + // Found at least one resolved record. + trySuccess(promise, finalResult); + return; } // No resolved address found. @@ -729,20 +726,13 @@ private void finishResolve(Promise<T> promise, Throwable cause) { if (cause == null) { // Only cache if the failure was not because of an IO error / timeout that was caused by the query // itself. - resolveCache.cache(hostname, additionals, unknownHostException, parent.ch.eventLoop()); + cache(hostname, additionals, unknownHostException); } else { unknownHostException.initCause(cause); } promise.tryFailure(unknownHostException); } - abstract boolean finishResolve(Class<? extends InetAddress> addressType, List<DnsCacheEntry> resolvedEntries, - Promise<T> promise); - - abstract DnsNameResolverContext<T> newResolverContext(DnsNameResolver parent, String hostname, - DnsRecord[] additionals, DnsCache resolveCache, - DnsServerAddressStream nameServerAddrs); - static String decodeDomainName(ByteBuf in) { in.markReaderIndex(); try { @@ -760,8 +750,8 @@ private DnsServerAddressStream getNameServers(String hostname) { return stream == null ? nameServerAddrs.duplicate() : stream; } - private void followCname( - DnsQuestion question, String cname, DnsQueryLifecycleObserver queryLifecycleObserver, Promise<T> promise) { + private void followCname(DnsQuestion question, String cname, DnsQueryLifecycleObserver queryLifecycleObserver, + Promise<List<T>> promise) { DnsServerAddressStream stream = getNameServers(cname); final DnsQuestion cnameQuestion; @@ -776,7 +766,7 @@ private void followCname( } private boolean query(String hostname, DnsRecordType type, DnsServerAddressStream dnsServerAddressStream, - Promise<T> promise, Throwable cause) { + Promise<List<T>> promise, Throwable cause) { final DnsQuestion question = newQuestion(hostname, type); if (question == null) { return false; @@ -785,9 +775,9 @@ private boolean query(String hostname, DnsRecordType type, DnsServerAddressStrea return true; } - private static DnsQuestion newQuestion(String hostname, DnsRecordType type) { + private DnsQuestion newQuestion(String hostname, DnsRecordType type) { try { - return new DefaultDnsQuestion(hostname, type); + return new DefaultDnsQuestion(hostname, type, dnsClass); } catch (IllegalArgumentException e) { // java.net.IDN.toASCII(...) may throw an IllegalArgumentException if it fails to parse the hostname return null;
diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java index 805121c7304..c0fdf83b945 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java @@ -28,6 +28,7 @@ import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.handler.codec.dns.DefaultDnsQuestion; import io.netty.handler.codec.dns.DnsQuestion; +import io.netty.handler.codec.dns.DnsRawRecord; import io.netty.handler.codec.dns.DnsRecord; import io.netty.handler.codec.dns.DnsRecordType; import io.netty.handler.codec.dns.DnsResponse; @@ -36,6 +37,7 @@ import io.netty.resolver.HostsFileEntriesResolver; import io.netty.resolver.ResolvedAddressTypes; import io.netty.util.NetUtil; +import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Future; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SocketUtils; @@ -52,6 +54,7 @@ import org.apache.directory.server.dns.messages.ResponseCode; import org.apache.directory.server.dns.store.DnsAttribute; import org.apache.directory.server.dns.store.RecordStore; +import org.hamcrest.Matchers; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -608,7 +611,7 @@ public void testQueryMx() throws Exception { buf.append(' '); buf.append(recordContent.readUnsignedShort()); buf.append(' '); - buf.append(DnsNameResolverContext.decodeDomainName(recordContent)); + buf.append(DnsResolveContext.decodeDomainName(recordContent)); } logger.info("{} has the following MX records:{}", hostname, buf); @@ -945,6 +948,84 @@ private static void testResolveAll0(ResolvedAddressTypes addressTypes, InetAddre } } + @Test + public void testResolveAllMx() { + final DnsNameResolver resolver = newResolver().build(); + try { + assertThat(resolver.isRecursionDesired(), is(true)); + + final Map<String, Future<List<DnsRecord>>> futures = new LinkedHashMap<String, Future<List<DnsRecord>>>(); + for (String name: DOMAINS) { + if (EXCLUSIONS_QUERY_MX.contains(name)) { + continue; + } + + futures.put(name, resolver.resolveAll(new DefaultDnsQuestion(name, DnsRecordType.MX))); + } + + for (Entry<String, Future<List<DnsRecord>>> e: futures.entrySet()) { + String hostname = e.getKey(); + Future<List<DnsRecord>> f = e.getValue().awaitUninterruptibly(); + + final List<DnsRecord> mxList = f.getNow(); + assertThat(mxList.size(), is(greaterThan(0))); + StringBuilder buf = new StringBuilder(); + for (DnsRecord r: mxList) { + ByteBuf recordContent = ((ByteBufHolder) r).content(); + + buf.append(StringUtil.NEWLINE); + buf.append('\t'); + buf.append(r.name()); + buf.append(' '); + buf.append(r.type().name()); + buf.append(' '); + buf.append(recordContent.readUnsignedShort()); + buf.append(' '); + buf.append(DnsResolveContext.decodeDomainName(recordContent)); + + ReferenceCountUtil.release(r); + } + + logger.info("{} has the following MX records:{}", hostname, buf); + } + } finally { + resolver.close(); + } + } + + @Test + public void testResolveAllHostsFile() { + final DnsNameResolver resolver = new DnsNameResolverBuilder(group.next()) + .channelType(NioDatagramChannel.class) + .hostsFileEntriesResolver(new HostsFileEntriesResolver() { + @Override + public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) { + if ("foo.com.".equals(inetHost)) { + try { + return InetAddress.getByAddress("foo.com", new byte[] { 1, 2, 3, 4 }); + } catch (UnknownHostException e) { + throw new Error(e); + } + } + return null; + } + }).build(); + + final List<DnsRecord> records = resolver.resolveAll(new DefaultDnsQuestion("foo.com.", A)) + .syncUninterruptibly().getNow(); + assertThat(records, Matchers.<DnsRecord>hasSize(1)); + assertThat(records.get(0), Matchers.<DnsRecord>instanceOf(DnsRawRecord.class)); + + final DnsRawRecord record = (DnsRawRecord) records.get(0); + final ByteBuf content = record.content(); + assertThat(record.name(), is("foo.com.")); + assertThat(record.dnsClass(), is(DnsRecord.CLASS_IN)); + assertThat(record.type(), is(A)); + assertThat(content.readableBytes(), is(4)); + assertThat(content.readInt(), is(0x01020304)); + record.release(); + } + @Test public void testResolveDecodeUnicode() { testResolveUnicode(true);
train
val
"2018-03-27T19:09:54"
"2018-03-19T09:32:53Z"
trustin
val
netty/netty/7790_7806
netty/netty
netty/netty/7790
netty/netty/7806
[ "keyword_issue_to_pr" ]
8189399e9d6a2e17e8d5b4665c86efb696792f56
fc3b145cbbcad4a257f92f0640eb4ded19b44afe
[ "Thats interesting... @carl-mastrangelo @ejona86 maybe you have some contacts we can loop in ? Generally speaking I think this should not happen as it woke-up the selector without reporting any events that need to be handled.", "CC @ericgribkoff", "This is reproducible on Android 8 for me as well. `selector.select()` returns immediately with OP_ACCEPT on the selected key set, then invoking `accept()` triggers an \"Invalid argument\" IOException from native code, and this just repeats indefinitely. I'm following up with some Android system folks about this, will update here if I get any additional information.", "@ericgribkoff thanks a lot! Also let us know if there is any workaround we can add in the meantime (I suspect there is none tho :( ).", "@normanmaurer From reading the code, I don't think it makes sense to continue trying to accept on the socket. You get back EINVAL which means it isn't listening anymore.\r\n\r\n@jox : any reason you aren't listening on all addresses? That would probably be more stable.", "I wonder if this can work around the problem here: https://github.com/netty/netty/pull/7806.\r\n\r\n@carl-mastrangelo the idea of continue reading here is that we also may get a `ENFILE` from which you can recover. That said I hope https://github.com/netty/netty/pull/7806 will \"workaround\" the issue. Please check ", "@jox can you test #7806 ?", "@normanmaurer one possibility is to map the error message back to the errno, since OpenJDK directly uses the message from `strerror_r`. This isn't a great solution, but it's feasible.", "I hope this was fixed by #7806 . If not please re-open", "I still have this issue on windows. I am using the following\r\n```\r\nWindows 10 Pro - 1803\r\nJVM 1.8.0_111 HotSpot\r\nNetty version 4.1.24.Final\r\n```\r\nI use [Ktor](https://github.com/ktorio/ktor) with Netty as the engine. My implementation:\r\n```kotlin\r\nfun main(args: Array<String>) {\r\n embeddedServer(Netty, port = 8080) {\r\n routing {\r\n get(\"/test\") {\r\n call.respondText(\"Hello world\")\r\n }\r\n }\r\n }.start(true)\r\n}\r\n```\r\nIt only happens when I test it with apache benchmark with Keep-Alive option enabled.\r\n```\r\nab -k -n 100000 -c 500 http://localhost:8080/test\r\n```\r\n\r\nAll the results seem to be passing, so the following error seems to happen after the connection closes:\r\n```\r\n[nettyCallPool-4-20] WARN io.netty.channel.nio.NioEventLoop - Selector.select() returned prematurely 512 times in a row; rebuilding Selector io.netty.channel.nio.SelectedSelectionKeySetSelector@61246795.\r\n```\r\n\r\nAlso when I limit `connectionGroupSize` to 1 (default on my machine is 5) the error is not showing up anymore:\r\n```kotlin\r\nembeddedServer(Netty, port = 8080, configure = {\r\n connectionGroupSize = 1\r\n })\r\n```\r\n", "@adhesivee can you also reproduce on linux or Mac ?", "I tried it on linux and could not reproduce. I have no Mac to test on.", "@adhesivee bummer... I will need to setup a windows vm then and try to reproduce. Would be useful if you could commit a full reproducer that I can run to GitHub and link it here.", "I created a setup which causes the issue on my machine: https://github.com/adhesivee/ktor-hello-sample", "@adhesivee I can not reproduce on windows server 2012. Can you tell me which ab version you use ?", "I am using:\r\n```\r\nThis is ApacheBench, Version 2.3 <$Revision: 1748469 $>\r\n```", "hmm ... I am using\r\n\r\n```\r\nC:\\Workspaces\\Apache24\\bin>ab.exe -V\r\nThis is ApacheBench, Version 2.3 <$Revision: 1826891 $>\r\nCopyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.ne\r\nLicensed to The Apache Software Foundation, http://www.apache.org/\r\n```\r\n\r\nAll just works :(", "One note though I did not get these exception while the debugger was enabled. \r\nAnd it only happened with Keep-Alive. Still I don't think it causes to much harm, because it seems to happen after the connection closes.", "@adhesivee does it happen all the time ?", "Also do I need to setup any logging etc to see it ?", "The default logging (info level) is enough to see it. \r\nIt does not always happen on the first ab run, but on the second run I always have quite some messages.", "very odd... I am running it in a loop at the moment and did not see it yet ... ", "@adhesivee would it be possible to share a thread dump / head dump when it happens ?\r\n", "It would also be good if you could try to run with `-Dio.netty.selectorAutoRebuildThreshold=100000000` and check the cpu usage. In this case when the \"problem\" happens you should see a very high cpu usage. Once this happens I would like to see a thread dump / heap dump.", "Is this format ok?\r\n[heapdump-1536236928163.zip](https://github.com/netty/netty/files/2357016/heapdump-1536236928163.zip)\r\n", "Yes this format is good... The important would be to have it taken when it happens.", "I think it is captures but I am not sure. Sometimes the logger writes a moment later then when the event really happens, to make things more complicated ofcourse.", "@adhesivee thats why I asked to run with \"-Dio.netty.selectorAutoRebuildThreshold=100000000\". This way you should detect the CPU usage goes up and then you can take the dump... That said it will not log then.", "Ok I have done as you said. I have done 2 dumps in the same process while processor being at 100%.\r\nI also change the benchmark a bit, this gives me the most of the messages:\r\n```\r\nab -k -n 200000 -c 100 http://localhost:8080/test\r\n```\r\n[heapdump-1536237736820.zip](https://github.com/netty/netty/files/2357053/heapdump-1536237736820.zip)\r\n", "@adhesivee cool thanks! Can I also have a few thread-dumps using `jstack` of the time it happens ?", "I am not that familiar with `jstack` I ran it like this\r\n```\r\njstack -J-d64 -m -l 6124\r\n```\r\n\r\nThe output I got is this:\r\n```\r\nAttaching to process ID 6124, please wait...\r\nDebugger attached successfully.\r\nServer compiler detected.\r\nJVM version is 25.111-b14\r\nDeadlock Detection:\r\n\r\nNo deadlocks found.\r\n\r\n----------------- 0 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n0xec8b485741564155 ????????\r\nsun.jvm.hotspot.debugger.DebuggerException: Windbg Error: ReadVirtual failed!\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readBytesFromProcess0(Native Method)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readBytesFromProcess(WindbgDebuggerLocal.java:490)\r\n at sun.jvm.hotspot.debugger.DebuggerBase$Fetcher.fetchPage(DebuggerBase.java:80)\r\n at sun.jvm.hotspot.debugger.PageCache.getPage(PageCache.java:178)\r\n at sun.jvm.hotspot.debugger.PageCache.getLong(PageCache.java:100)\r\n at sun.jvm.hotspot.debugger.DebuggerBase.readCInteger(DebuggerBase.java:364)\r\n at sun.jvm.hotspot.debugger.DebuggerBase.readAddressValue(DebuggerBase.java:462)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readAddress(WindbgDebuggerLocal.java:316)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgAddress.getAddressAt(WindbgAddress.java:72)\r\n at sun.jvm.hotspot.debugger.windows.amd64.WindowsAMD64CFrame.sender(WindowsAMD64CFrame.java:60)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:161)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:58)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:53)\r\n at sun.jvm.hotspot.tools.JStack.run(JStack.java:66)\r\n at sun.jvm.hotspot.tools.Tool.startInternal(Tool.java:260)\r\n at sun.jvm.hotspot.tools.Tool.start(Tool.java:223)\r\n at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)\r\n at sun.jvm.hotspot.tools.JStack.main(JStack.java:92)\r\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n at java.lang.reflect.Method.invoke(Method.java:498)\r\n at sun.tools.jstack.JStack.runJStackTool(JStack.java:140)\r\n at sun.tools.jstack.JStack.main(JStack.java:106)\r\n----------------- 1 -----------------\r\n----------------- 2 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 3 -----------------\r\n----------------- 4 -----------------\r\n----------------- 5 -----------------\r\n----------------- 6 -----------------\r\n----------------- 7 -----------------\r\n----------------- 8 -----------------\r\n----------------- 9 -----------------\r\n----------------- 10 -----------------\r\n----------------- 11 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n----------------- 12 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 13 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 14 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 15 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 16 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 17 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 18 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 19 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 20 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 21 -----------------\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 22 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n----------------- 23 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 24 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n0x000000001fe86040 ????????\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 25 -----------------\r\n----------------- 26 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 27 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 28 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\n0x0101010101010101 ????????\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 29 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 30 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 31 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 32 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 33 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n0x0000000021955fd0 ????????\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 34 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 35 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n0x0000000021b56120 ????????\r\n0x0000000000000001 ????????\r\nsun.jvm.hotspot.debugger.DebuggerException: Windbg Error: ReadVirtual failed!\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readBytesFromProcess0(Native Method)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readBytesFromProcess(WindbgDebuggerLocal.java:490)\r\n at sun.jvm.hotspot.debugger.DebuggerBase$Fetcher.fetchPage(DebuggerBase.java:80)\r\n at sun.jvm.hotspot.debugger.PageCache.getPage(PageCache.java:178)\r\n at sun.jvm.hotspot.debugger.PageCache.getLong(PageCache.java:100)\r\n at sun.jvm.hotspot.debugger.DebuggerBase.readCInteger(DebuggerBase.java:364)\r\n at sun.jvm.hotspot.debugger.DebuggerBase.readAddressValue(DebuggerBase.java:462)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgDebuggerLocal.readAddress(WindbgDebuggerLocal.java:316)\r\n at sun.jvm.hotspot.debugger.windbg.WindbgAddress.getAddressAt(WindbgAddress.java:72)\r\n at sun.jvm.hotspot.debugger.windows.amd64.WindowsAMD64CFrame.sender(WindowsAMD64CFrame.java:60)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:161)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:58)\r\n at sun.jvm.hotspot.tools.PStack.run(PStack.java:53)\r\n at sun.jvm.hotspot.tools.JStack.run(JStack.java:66)\r\n at sun.jvm.hotspot.tools.Tool.startInternal(Tool.java:260)\r\n at sun.jvm.hotspot.tools.Tool.start(Tool.java:223)\r\n at sun.jvm.hotspot.tools.Tool.execute(Tool.java:118)\r\n at sun.jvm.hotspot.tools.JStack.main(JStack.java:92)\r\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n at java.lang.reflect.Method.invoke(Method.java:498)\r\n at sun.tools.jstack.JStack.runJStackTool(JStack.java:140)\r\n at sun.tools.jstack.JStack.main(JStack.java:106)\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 36 -----------------\r\n0x00007fffdcd69f34 ntdll!NtWaitForSingleObject + 0x14\r\n0x0000000021c55ed0 ????????\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 37 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n----------------- 38 -----------------\r\n0x00007fffdcd69f94 ntdll!ZwDeviceIoControlFile + 0x14\r\nLocked ownable synchronizers:\r\n - None\r\n```", "@adhesivee please use `jstack <pid>`.", "This is printed:\r\n```\r\nDebugger attached successfully.\r\nServer compiler detected.\r\nJVM version is 25.111-b14\r\nDeadlock Detection:\r\n\r\nNo deadlocks found.\r\n\r\nThread 37: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(long, int, int[], int[], int[], long) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll() @bci=43, line=296 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(sun.nio.ch.WindowsSelectorImpl$SubSelector) @bci=1, line=278 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=63, line=159 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 36: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=131, line=174 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 35: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=131, line=174 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 34: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=32, line=144 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 33: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=131, line=174 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 32: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=131, line=174 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 31: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(long, int, int[], int[], int[], long) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll() @bci=43, line=296 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(sun.nio.ch.WindowsSelectorImpl$SubSelector) @bci=1, line=278 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=63, line=159 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 30: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(long, int, int[], int[], int[], long) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll() @bci=43, line=296 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(sun.nio.ch.WindowsSelectorImpl$SubSelector) @bci=1, line=278 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=63, line=159 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 29: (state = BLOCKED)\r\n - sun.nio.ch.WindowsSelectorImpl.wakeup() @bci=6, line=604 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.wakeup() @bci=4, line=73 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.wakeup(boolean) @bci=20, line=708 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor.execute(java.lang.Runnable) @bci=68, line=774 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=46, line=391 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelReadComplete() @bci=4, line=444 (Compiled frame)\r\n - io.netty.handler.codec.ByteToMessageDecoder.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=48, line=324 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=43, line=263 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline$HeadContext.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=1439 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline.fireChannelReadComplete() @bci=4, line=971 (Compiled frame)\r\n - io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read() @bci=186, line=168 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKey(java.nio.channels.SelectionKey, io.netty.channel.nio.AbstractNioChannel) @bci=119, line=645 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized() @bci=51, line=580 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeys() @bci=8, line=497 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=126, line=459 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 28: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=131, line=174 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 27: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket0(int) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl.resetWakeupSocket() @bci=22, line=473 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=32, line=144 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 26: (state = BLOCKED)\r\n - sun.nio.ch.WindowsSelectorImpl.wakeup() @bci=6, line=604 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.wakeup() @bci=4, line=73 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.wakeup(boolean) @bci=20, line=708 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor.execute(java.lang.Runnable) @bci=68, line=774 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=46, line=391 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelReadComplete() @bci=4, line=444 (Compiled frame)\r\n - io.netty.handler.codec.ByteToMessageDecoder.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=48, line=324 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=43, line=263 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline$HeadContext.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=1439 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline.fireChannelReadComplete() @bci=4, line=971 (Compiled frame)\r\n - io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read() @bci=186, line=168 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKey(java.nio.channels.SelectionKey, io.netty.channel.nio.AbstractNioChannel) @bci=119, line=645 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized() @bci=51, line=580 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeys() @bci=8, line=497 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=126, line=459 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 25: (state = BLOCKED)\r\n - sun.nio.ch.WindowsSelectorImpl.wakeup() @bci=6, line=604 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.wakeup() @bci=4, line=73 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.wakeup(boolean) @bci=20, line=708 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor.execute(java.lang.Runnable) @bci=68, line=774 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=46, line=391 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=97 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelReadComplete() @bci=4, line=444 (Compiled frame)\r\n - io.netty.handler.codec.ByteToMessageDecoder.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=48, line=324 (Compiled frame)\r\n - io.netty.channel.CombinedChannelDuplexHandler.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=43, line=263 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.fireChannelReadComplete() @bci=4, line=373 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline$HeadContext.channelReadComplete(io.netty.channel.ChannelHandlerContext) @bci=1, line=1439 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete() @bci=15, line=398 (Compiled frame)\r\n - io.netty.channel.AbstractChannelHandlerContext.invokeChannelReadComplete(io.netty.channel.AbstractChannelHandlerContext) @bci=15, line=380 (Compiled frame)\r\n - io.netty.channel.DefaultChannelPipeline.fireChannelReadComplete() @bci=4, line=971 (Compiled frame)\r\n - io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read() @bci=186, line=168 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKey(java.nio.channels.SelectionKey, io.netty.channel.nio.AbstractNioChannel) @bci=119, line=645 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized() @bci=51, line=580 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.processSelectedKeys() @bci=8, line=497 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=126, line=459 (Compiled frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 24: (state = IN_NATIVE)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(long, int, int[], int[], int[], long) @bci=0 (Compiled frame; information may be imprecise)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.poll() @bci=43, line=296 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(sun.nio.ch.WindowsSelectorImpl$SubSelector) @bci=1, line=278 (Compiled frame)\r\n - sun.nio.ch.WindowsSelectorImpl.doSelect(long) @bci=63, line=159 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.lockAndDoSelect(long) @bci=37, line=86 (Compiled frame)\r\n - sun.nio.ch.SelectorImpl.select(long) @bci=30, line=97 (Compiled frame)\r\n - io.netty.channel.nio.SelectedSelectionKeySetSelector.select(long) @bci=12, line=62 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.select(boolean) @bci=91, line=753 (Compiled frame)\r\n - io.netty.channel.nio.NioEventLoop.run() @bci=56, line=409 (Interpreted frame)\r\n - io.netty.util.concurrent.SingleThreadEventExecutor$5.run() @bci=44, line=884 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 23: (state = BLOCKED)\r\n - java.lang.Object.wait(long) @bci=0 (Interpreted frame)\r\n - java.lang.ref.ReferenceQueue.remove(long) @bci=59, line=143 (Compiled frame)\r\n - io.netty.util.internal.ObjectCleaner$1.run() @bci=20, line=54 (Interpreted frame)\r\n - io.netty.util.concurrent.FastThreadLocalRunnable.run() @bci=4, line=30 (Interpreted frame)\r\n - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame)\r\n\r\n\r\nThread 16: (state = IN_NATIVE)\r\n - java.net.SocketInputStream.socketRead0(java.io.FileDescriptor, byte[], int, int, int) @bci=0 (Interpreted frame)\r\n - java.net.SocketInputStream.socketRead(java.io.FileDescriptor, byte[], int, int, int) @bci=8, line=116 (Interpreted frame)\r\n - java.net.SocketInputStream.read(byte[], int, int, int) @bci=79, line=170 (Interpreted frame)\r\n - java.net.SocketInputStream.read(byte[], int, int) @bci=11, line=141 (Interpreted frame)\r\n - sun.nio.cs.StreamDecoder.readBytes() @bci=135, line=284 (Interpreted frame)\r\n - sun.nio.cs.StreamDecoder.implRead(char[], int, int) @bci=112, line=326 (Interpreted frame)\r\n - sun.nio.cs.StreamDecoder.read(char[], int, int) @bci=180, line=178 (Interpreted frame)\r\n - java.io.InputStreamReader.read(char[], int, int) @bci=7, line=184 (Interpreted frame)\r\n - java.io.BufferedReader.fill() @bci=145, line=161 (Interpreted frame)\r\n - java.io.BufferedReader.readLine(boolean) @bci=44, line=324 (Interpreted frame)\r\n - java.io.BufferedReader.readLine() @bci=2, line=389 (Interpreted frame)\r\n - com.intellij.rt.execution.application.AppMainV2$1.run() @bci=36, line=64 (Interpreted frame)\r\n\r\n\r\nThread 15: (state = BLOCKED)\r\n\r\n\r\nThread 14: (state = BLOCKED)\r\n\r\n\r\nThread 13: (state = BLOCKED)\r\n - java.lang.Object.wait(long) @bci=0 (Interpreted frame)\r\n - java.lang.ref.ReferenceQueue.remove(long) @bci=59, line=143 (Compiled frame)\r\n - java.lang.ref.ReferenceQueue.remove() @bci=2, line=164 (Compiled frame)\r\n - java.lang.ref.Finalizer$FinalizerThread.run() @bci=36, line=209 (Interpreted frame)\r\n\r\n\r\nThread 12: (state = BLOCKED)\r\n - java.lang.Object.wait(long) @bci=0 (Interpreted frame)\r\n - java.lang.Object.wait() @bci=2, line=502 (Compiled frame)\r\n - java.lang.ref.Reference.tryHandlePending(boolean) @bci=54, line=191 (Compiled frame)\r\n - java.lang.ref.Reference$ReferenceHandler.run() @bci=1, line=153 (Interpreted frame)\r\n\r\n\r\nThread 2: (state = BLOCKED)\r\n - java.lang.Object.wait(long) @bci=0 (Interpreted frame)\r\n - java.lang.Object.wait() @bci=2, line=502 (Interpreted frame)\r\n - io.netty.util.concurrent.DefaultPromise.await() @bci=47, line=231 (Interpreted frame)\r\n - io.netty.channel.DefaultChannelPromise.await() @bci=1, line=131 (Interpreted frame)\r\n - io.netty.channel.DefaultChannelPromise.await() @bci=1, line=30 (Interpreted frame)\r\n - io.netty.util.concurrent.DefaultPromise.sync() @bci=1, line=337 (Interpreted frame)\r\n - io.netty.channel.DefaultChannelPromise.sync() @bci=1, line=119 (Interpreted frame)\r\n - io.netty.channel.DefaultChannelPromise.sync() @bci=1, line=30 (Interpreted frame)\r\n - io.ktor.server.netty.NettyApplicationEngine.start(boolean) @bci=403, line=96 (Interpreted frame)\r\n - nl.myndocs.MainKt.main(java.lang.String[]) @bci=34, line=17 (Interpreted frame)\r\n```" ]
[]
"2018-03-23T07:11:05Z"
[]
Infinite Selector rebuild loop of death.
I'm experiencing an issue that has been reported about before. None of the reports are giving me any hints though. (e.g. #2426 and #2616) The problem: I'm starting a Websocket server with ServerBootstrap bound to the wifi IP address on Android. As soon the wifi connection changes or wifi is disabled completely, the log will be flooded with the following two messages, repeated about 100 times per second while the app is not usable anymore. ``` W/NioEventLoop: Selector.select() returned prematurely 512 times in a row; rebuilding Selector sun.nio.ch.PollSelectorImpl@e54f195. I/NioEventLoop: Migrated 1 channel(s) to the new Selector. ``` ### Steps to reproduce Run the below code on an android device and while the app is running switch off wifi or change to another wifi hotspot. ### Minimal yet complete reproducer code (or URL to code) ``` java import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.common.net.InetAddresses; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteOrder; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpServerCodec; public class MainActivity extends AppCompatActivity { private EventLoopGroup group; protected InetSocketAddress localAddress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localAddress = new InetSocketAddress(getLocalIPAddress(this), 0); group = new NioEventLoopGroup(); ServerBootstrap tcp = new ServerBootstrap(); tcp.group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { addLast("server", ch.pipeline(), new HttpServerCodec() ); } }); tcp.bind(localAddress); ChannelFuture future = tcp.bind(localAddress); try { future.sync(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void addLast(String prefix, ChannelPipeline pipeline, ChannelHandler... channelHandlers) { for (ChannelHandler handler : channelHandlers) { String name = (prefix + handler.getClass().getSimpleName()).intern(); pipeline.addLast(name, handler); } } protected EventLoopGroup newEventLoopGroup(int maxChannels) { return new NioEventLoopGroup(maxChannels); } protected final EventLoopGroup newEventLoopGroup() { return newEventLoopGroup(0); } public static InetAddress getLocalIPAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ip = wifiInfo.getIpAddress(); if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ip = Integer.reverseBytes(ip); } return InetAddresses.fromInteger(ip); } } ``` ``` dependencies { ... implementation 'io.netty:netty-codec-http:4.1.22.Final' implementation 'io.netty:netty-handler:4.1.22.Final' implementation 'com.google.guava:guava:20.0' ... } ``` ### Netty version 4.1.22.Final ### JVM version (e.g. `java -version`) 7 ### OS version (e.g. `uname -a`) Android 7.0
[ "transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java", "transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java" ]
[ "transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java", "transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java" ]
[ "transport/src/test/java/io/netty/channel/socket/nio/NioServerSocketChannelTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java b/transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java index 3d05a461841..57dcc85e584 100644 --- a/transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java +++ b/transport/src/main/java/io/netty/channel/nio/AbstractNioMessageChannel.java @@ -172,11 +172,19 @@ protected boolean continueOnWriteError() { } protected boolean closeOnReadError(Throwable cause) { - // ServerChannel should not be closed even on IOException because it can often continue - // accepting incoming connections. (e.g. too many open files) - return cause instanceof IOException && - !(cause instanceof PortUnreachableException) && - !(this instanceof ServerChannel); + if (!isActive()) { + // If the channel is not active anymore for whatever reason we should not try to continue reading. + return true; + } + if (cause instanceof PortUnreachableException) { + return false; + } + if (cause instanceof IOException) { + // ServerChannel should not be closed even on IOException because it can often continue + // accepting incoming connections. (e.g. too many open files) + return !(this instanceof ServerChannel); + } + return true; } /** diff --git a/transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java b/transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java index 12662127c1d..f2d6f16f656 100644 --- a/transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java +++ b/transport/src/main/java/io/netty/channel/socket/nio/NioServerSocketChannel.java @@ -200,4 +200,10 @@ protected void autoReadCleared() { clearReadPending(); } } + + // Override just to to be able to call directly via unit tests. + @Override + protected boolean closeOnReadError(Throwable cause) { + return super.closeOnReadError(cause); + } }
diff --git a/transport/src/test/java/io/netty/channel/socket/nio/NioServerSocketChannelTest.java b/transport/src/test/java/io/netty/channel/socket/nio/NioServerSocketChannelTest.java new file mode 100644 index 00000000000..80779902f76 --- /dev/null +++ b/transport/src/test/java/io/netty/channel/socket/nio/NioServerSocketChannelTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.channel.socket.nio; + +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import org.junit.Assert; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.channels.ServerSocketChannel; + +public class NioServerSocketChannelTest { + + @Test + public void testCloseOnError() throws Exception { + ServerSocketChannel jdkChannel = ServerSocketChannel.open(); + NioServerSocketChannel serverSocketChannel = new NioServerSocketChannel(jdkChannel); + EventLoopGroup group = new NioEventLoopGroup(1); + try { + group.register(serverSocketChannel).syncUninterruptibly(); + serverSocketChannel.bind(new InetSocketAddress(0)).syncUninterruptibly(); + Assert.assertFalse(serverSocketChannel.closeOnReadError(new IOException())); + Assert.assertTrue(serverSocketChannel.closeOnReadError(new IllegalArgumentException())); + serverSocketChannel.close().syncUninterruptibly(); + } finally { + group.shutdownGracefully(); + } + } +}
train
val
"2018-03-23T07:39:17"
"2018-03-17T17:47:18Z"
jox
val
netty/netty/7804_7813
netty/netty
netty/netty/7804
netty/netty/7813
[ "keyword_pr_to_issue" ]
5ebee9426f05b0c9287bf8c0e27e9e37e1d96c66
965734a1eb1f2553985094ade9f28871016f652b
[ "You are right...\nWant to do a pr?\n\n> Am 22.03.2018 um 17:58 schrieb Fabian Lange <notifications@github.com>:\n> \n> (running io.netty.buffer:4.1.21.Final)\n> \n> I have a Java Output stream (java.io.OutputStream) I want to incrementally copy a ByteBuffer too.\n> \n> The byte buffer is off heap and big.\n> I naively used:\n> public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException;\n> \n> assuming that it would copy all the data to the output stream.\n> \n> It does, but to do so it copies the whole native buffer into the heap! I do not have that much heap, resulting in:\n> \n> java.lang.OutOfMemoryError: Java heap space \n> at io.netty.util.internal.PlatformDependent.allocateUninitializedArray(PlatformDependent.java:200) ~[40:io.netty.common:4.1.21.Final] \n> at io.netty.buffer.UnpooledUnsafeHeapByteBuf.allocateArray(UnpooledUnsafeHeapByteBuf.java:34) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf.allocateArray(UnpooledByteBufAllocator.java:144) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledHeapByteBuf.<init>(UnpooledHeapByteBuf.java:60) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledUnsafeHeapByteBuf.<init>(UnpooledUnsafeHeapByteBuf.java:29) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf.<init>(UnpooledByteBufAllocator.java:139) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledByteBufAllocator.newHeapBuffer(UnpooledByteBufAllocator.java:82) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:166) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:157) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnsafeByteBufUtil.getBytes(UnsafeByteBufUtil.java:572) ~[34:io.netty.buffer:4.1.21.Final] \n> at io.netty.buffer.UnpooledUnsafeDirectByteBuf.getBytes(UnpooledUnsafeDirectByteBuf.java:365) ~[34:io.netty.buffer:4.1.21.Final] \n> I checked io.netty.buffer.UnsafeByteBufUtil.getBytes(AbstractByteBuf, long, int, OutputStream, int)\n> and behold. It creates a heap bytebuffer of that size to copy the array into it and then to copy that to the output stream.\n> \n> Bummer!\n> \n> Shouldn't netty do this better by itself? it seems that I need to manually do this by using a (reasonably sized) byte array and read from byteBuf into that and flush that to my stream in a loop\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n", "Doing a userspace fix for my immediate need right now. \r\nThe question for a netty internal implementation would be how big that buffer should be. right now its full size, so it can do that in one pass.\r\nThe typical buffer size is 8k. do we want this configurable (yet another method overload?)", "I think just using 8k (or less if the ByteBuf is smaller ) is ok for now \n\n> Am 22.03.2018 um 18:05 schrieb Fabian Lange <notifications@github.com>:\n> \n> Doing a userspace fix for my immediate need right now.\n> The question for a netty internal implementation would be how big that buffer should be. right now its full size, so it can do that in one pass.\n> The typical buffer size is 8k. do we want this configurable (yet another method overload?)\n> \n> —\n> You are receiving this because you commented.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n" ]
[ "changes -> chances", "How about:\r\n- addr -> inAddr\r\n- array -> in\r\n- offset -> inOffset\r\n- chunkLen -> inLen\r\n- length -> outLen", "Can we just do: `Math.min(Math.min(length, ByteBufUtil.WRITE_CHUNK_SIZE), length)`? This would eliminate the reason to pass 2 length parameters to the `getBytes()` below.", "hmm wouldn't we still need it ? I am confused why we not need it with this change ... Can you explain", "done", "Because I'm an idiot? Didn't notice `outLen` is updated at the end of the loop. :-)", "when I tried to improve this I was wondering if we can avoid that duplicate call?", "@CodingFabian nope we can't... `internal` will be false if you use `get*`. This is needed as it may be called from multiple threads at the same time which should be fine as you not expect to do any internal updates on the indices. If you use a `get*` method there will be no duplicate invoked ", "lol ok that explains why =P", "so you decided against using alloc() to get this temp array?", "let me check if its possible here as well (in the `Unsafe` portion it is.", "fixed @CodingFabian " ]
"2018-03-28T09:35:40Z"
[]
Transferring a ByteBuf to Outputstream without duplicating memory
(running io.netty.buffer:4.1.21.Final) I have a Java Output stream (java.io.OutputStream) I want to incrementally copy a ByteBuffer too. The byte buffer is off heap and big. I naively used: public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException; assuming that it would copy all the data to the output stream. It does, but to do so it copies the whole native buffer into the heap! I do not have that much heap, resulting in: ``` java.lang.OutOfMemoryError: Java heap space at io.netty.util.internal.PlatformDependent.allocateUninitializedArray(PlatformDependent.java:200) ~[40:io.netty.common:4.1.21.Final] at io.netty.buffer.UnpooledUnsafeHeapByteBuf.allocateArray(UnpooledUnsafeHeapByteBuf.java:34) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf.allocateArray(UnpooledByteBufAllocator.java:144) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledHeapByteBuf.<init>(UnpooledHeapByteBuf.java:60) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledUnsafeHeapByteBuf.<init>(UnpooledUnsafeHeapByteBuf.java:29) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf.<init>(UnpooledByteBufAllocator.java:139) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledByteBufAllocator.newHeapBuffer(UnpooledByteBufAllocator.java:82) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:166) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.AbstractByteBufAllocator.heapBuffer(AbstractByteBufAllocator.java:157) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnsafeByteBufUtil.getBytes(UnsafeByteBufUtil.java:572) ~[34:io.netty.buffer:4.1.21.Final] at io.netty.buffer.UnpooledUnsafeDirectByteBuf.getBytes(UnpooledUnsafeDirectByteBuf.java:365) ~[34:io.netty.buffer:4.1.21.Final] ``` I checked io.netty.buffer.UnsafeByteBufUtil.getBytes(AbstractByteBuf, long, int, OutputStream, int) and behold. It creates a heap bytebuffer of that size to copy the array into it and then to copy that to the output stream. Bummer! Shouldn't netty do this better by itself? it seems that I need to manually do this by using a (reasonably sized) byte array and read from byteBuf into that and flush that to my stream in a loop
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java" ]
[ "buffer/src/main/java/io/netty/buffer/ByteBufUtil.java", "buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java", "buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java" ]
[]
diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index b0ecb35cace..768f5587146 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -27,6 +27,8 @@ import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; +import java.io.IOException; +import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; @@ -64,6 +66,7 @@ protected CharBuffer initialValue() throws Exception { private static final int MAX_BYTES_PER_CHAR_UTF8 = (int) CharsetUtil.encoder(CharsetUtil.UTF_8).maxBytesPerChar(); + static final int WRITE_CHUNK_SIZE = 8192; static final ByteBufAllocator DEFAULT_ALLOCATOR; static { @@ -1392,5 +1395,43 @@ private static boolean isUtf8(ByteBuf buf, int index, int length) { return true; } + /** + * Read bytes from the given {@link ByteBuffer} into the given {@link OutputStream} using the {@code position} and + * {@code length}. The position and limit of the given {@link ByteBuffer} may be adjusted. + */ + static void readBytes(ByteBufAllocator allocator, ByteBuffer buffer, int position, int length, OutputStream out) + throws IOException { + if (buffer.hasArray()) { + out.write(buffer.array(), position + buffer.arrayOffset(), length); + } else { + int chunkLen = Math.min(length, WRITE_CHUNK_SIZE); + buffer.clear().position(position); + + if (allocator.isDirectBufferPooled()) { + // if direct buffers are pooled chances are good that heap buffers are pooled as well. + ByteBuf tmpBuf = allocator.heapBuffer(chunkLen); + try { + byte[] tmp = tmpBuf.array(); + int offset = tmpBuf.arrayOffset(); + getBytes(buffer, tmp, offset, chunkLen, out, length); + } finally { + tmpBuf.release(); + } + } else { + getBytes(buffer, new byte[chunkLen], 0, chunkLen, out, length); + } + } + } + + private static void getBytes(ByteBuffer inBuffer, byte[] in, int inOffset, int inLen, OutputStream out, int outLen) + throws IOException { + do { + int len = Math.min(inLen, outLen); + inBuffer.get(in, inOffset, len); + out.write(in, inOffset, len); + outLen -= len; + } while (outLen > 0); + } + private ByteBufUtil() { } } diff --git a/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java index 7c6192bf076..3c43509c054 100644 --- a/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/PooledDirectByteBuf.java @@ -190,17 +190,7 @@ private void getBytes(int index, OutputStream out, int length, boolean internal) if (length == 0) { return; } - - byte[] tmp = new byte[length]; - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = memory.duplicate(); - } - tmpBuf.clear().position(idx(index)); - tmpBuf.get(tmp); - out.write(tmp); + ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : memory.duplicate(), idx(index), length, out); } @Override diff --git a/buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java b/buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java index 3ce75d1d637..49960b37641 100644 --- a/buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/UnpooledDirectByteBuf.java @@ -491,21 +491,7 @@ private void getBytes(int index, OutputStream out, int length, boolean internal) if (length == 0) { return; } - - if (buffer.hasArray()) { - out.write(buffer.array(), index + buffer.arrayOffset(), length); - } else { - byte[] tmp = new byte[length]; - ByteBuffer tmpBuf; - if (internal) { - tmpBuf = internalNioBuffer(); - } else { - tmpBuf = buffer.duplicate(); - } - tmpBuf.clear().position(index); - tmpBuf.get(tmp); - out.write(tmp); - } + ByteBufUtil.readBytes(alloc(), internal ? internalNioBuffer() : buffer.duplicate(), index, length, out); } @Override diff --git a/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java index 1016cc4ab93..7d866d5b433 100644 --- a/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/UnsafeByteBufUtil.java @@ -583,18 +583,34 @@ private static void setSingleBytes(final AbstractByteBuf buf, final long addr, f static void getBytes(AbstractByteBuf buf, long addr, int index, OutputStream out, int length) throws IOException { buf.checkIndex(index, length); if (length != 0) { - ByteBuf tmpBuf = buf.alloc().heapBuffer(length); - try { - byte[] tmp = tmpBuf.array(); - int offset = tmpBuf.arrayOffset(); - PlatformDependent.copyMemory(addr, tmp, offset, length); - out.write(tmp, offset, length); - } finally { - tmpBuf.release(); + int len = Math.min(length, ByteBufUtil.WRITE_CHUNK_SIZE); + if (buf.alloc().isDirectBufferPooled()) { + // if direct buffers are pooled chances are good that heap buffers are pooled as well. + ByteBuf tmpBuf = buf.alloc().heapBuffer(len); + try { + byte[] tmp = tmpBuf.array(); + int offset = tmpBuf.arrayOffset(); + getBytes(addr, tmp, offset, len, out, length); + } finally { + tmpBuf.release(); + } + } else { + getBytes(addr, new byte[len], 0, len, out, length); } } } + private static void getBytes(long inAddr, byte[] in, int inOffset, int inLen, OutputStream out, int outLen) + throws IOException { + do { + int len = Math.min(inLen, outLen); + PlatformDependent.copyMemory(inAddr, in, inOffset, len); + out.write(in, inOffset, len); + outLen -= len; + inAddr += len; + } while (outLen > 0); + } + static void setZero(long addr, int length) { if (length == 0) { return;
null
val
val
"2018-03-27T19:09:54"
"2018-03-22T16:58:51Z"
CodingFabian
val
netty/netty/7820_7821
netty/netty
netty/netty/7820
netty/netty/7821
[ "keyword_pr_to_issue", "timestamp(timedelta=0.0, similarity=0.9128726367498636)" ]
cd4594d29244f7bea9d718e74ec4ecdcb6c62c13
c58069f2849837aaaaa13aa4cb00b83c32966623
[]
[]
"2018-03-30T13:46:35Z"
[ "defect" ]
JsonObjectDecoder to better handle streaming data
### Description There seems to be a long running issue with several iterations of fixes for streaming of different types of JSON data: - The [6156](https://github.com/netty/netty/issues/6156) was the original issue which made the internal index reset together with resetting the decoder state, but it did not cover the case with streaming arrays. - The [6969](https://github.com/netty/netty/issues/6969) fixed the problem with arrays, but did not cover the case with streaming objects. - The [7722](https://github.com/netty/netty/issues/7722) is a (currently) opened issue which fixes the problem with streaming objects. While the described solution seems to workaround the problem, it causes multiple reads of the same bytes and technically does not fully recover the state (different branches are executed for the repeated reads). A better approach seems to be to just properly recover the internal decoder index given the information about how far the decoder went from the readerIndex and the last readerIndex are already there which seems to cover both the cases with streaming arrays and objects. ### Netty version 4.1.22.Final
[ "codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java" ]
[ "codec/src/test/java/io/netty/handler/codec/json/JsonObjectDecoderTest.java" ]
diff --git a/codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java b/codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java index 123618b1437..f63e62066ee 100644 --- a/codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java @@ -91,11 +91,7 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) t } if (this.idx > in.readerIndex() && lastReaderIndex != in.readerIndex()) { - this.idx = in.readerIndex(); - if (state == ST_DECODING_ARRAY_STREAM) { - insideString = false; - openBraces = 1; - } + this.idx = in.readerIndex() + (idx - lastReaderIndex); } // index of next byte to process.
diff --git a/codec/src/test/java/io/netty/handler/codec/json/JsonObjectDecoderTest.java b/codec/src/test/java/io/netty/handler/codec/json/JsonObjectDecoderTest.java index 12eb13ac19c..d29654f2491 100644 --- a/codec/src/test/java/io/netty/handler/codec/json/JsonObjectDecoderTest.java +++ b/codec/src/test/java/io/netty/handler/codec/json/JsonObjectDecoderTest.java @@ -47,6 +47,27 @@ public void testJsonObjectOverMultipleWrites() { assertFalse(ch.finish()); } + @Test + public void testMultipleJsonObjectsOverMultipleWrites() { + EmbeddedChannel ch = new EmbeddedChannel(new JsonObjectDecoder()); + + String objectPart1 = "{\"name\":\"Jo"; + String objectPart2 = "hn\"}{\"name\":\"John\"}{\"name\":\"Jo"; + String objectPart3 = "hn\"}"; + + ch.writeInbound(Unpooled.copiedBuffer(objectPart1, CharsetUtil.UTF_8)); + ch.writeInbound(Unpooled.copiedBuffer(objectPart2, CharsetUtil.UTF_8)); + ch.writeInbound(Unpooled.copiedBuffer(objectPart3, CharsetUtil.UTF_8)); + + for (int i = 0; i < 3; i++) { + ByteBuf res = ch.readInbound(); + assertEquals("{\"name\":\"John\"}", res.toString(CharsetUtil.UTF_8)); + res.release(); + } + + assertFalse(ch.finish()); + } + @Test public void testJsonArrayOverMultipleWrites() { EmbeddedChannel ch = new EmbeddedChannel(new JsonObjectDecoder());
train
val
"2018-03-29T22:01:25"
"2018-03-30T13:18:38Z"
ikurovsky
val
netty/netty/7819_7822
netty/netty
netty/netty/7819
netty/netty/7822
[ "timestamp(timedelta=0.0, similarity=0.8806146228979717)", "keyword_pr_to_issue" ]
cd4594d29244f7bea9d718e74ec4ecdcb6c62c13
8d78893a76a8c14c18b304ffe1fce2dc43ed4206
[ "Yes this sounds good.... can you provide a PR?\n\n> Am 30.03.2018 um 14:24 schrieb Nicolae Mihalache <notifications@github.com>:\n> \n> Hello,\n> \n> I get an exception \"promise already done\" apparently caused by the ChunkedWriteHandler which is called twice for the same message, one from my flush and the other time from the channelWritabilityChanged.\n> \n> Not sure if the ChunkedWriteHandler.doFlush method is supposed to be called twice in the same write but it looks to work ok when it's called twice and the message is ChunkedInput.\n> \n> Maybe lines 304 and 305 should be reversed from:\n> \n> ctx.write(pendingMessage, currentWrite.promise);\n> this.currentWrite = null;\n> to:\n> \n> this.currentWrite = null;\n> ctx.write(pendingMessage, currentWrite.promise);\n> A stacktrace is attached.\n> stack-trace.txt\n> \n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n> \n" ]
[]
"2018-03-30T13:54:55Z"
[ "defect" ]
promise already done caused by ChunkedWriteHandler writing the same (non chunked) message twice
Hello, I get an exception "promise already done" apparently caused by the ChunkedWriteHandler which is called twice for the same message, one from my flush and the other time from the channelWritabilityChanged. Not sure if the ChunkedWriteHandler.doFlush method is supposed to be called twice in the same write but it looks to work ok when it's called twice and the message is ChunkedInput. Maybe lines 304 and 305 should be reversed from: ``` ctx.write(pendingMessage, currentWrite.promise); this.currentWrite = null; ``` to: ``` this.currentWrite = null; ctx.write(pendingMessage, currentWrite.promise); ``` A stacktrace is attached. [stack-trace.txt](https://github.com/netty/netty/files/1863541/stack-trace.txt)
[ "handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java" ]
[ "handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java index 1bc0c6bf81d..6f753c5c510 100644 --- a/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java +++ b/handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java @@ -299,8 +299,8 @@ public void operationComplete(ChannelFuture future) throws Exception { ctx.flush(); requiresFlush = false; } else { - ctx.write(pendingMessage, currentWrite.promise); this.currentWrite = null; + ctx.write(pendingMessage, currentWrite.promise); requiresFlush = true; }
null
val
val
"2018-03-29T22:01:25"
"2018-03-30T12:24:31Z"
xpromache
val
netty/netty/7823_7824
netty/netty
netty/netty/7823
netty/netty/7824
[ "keyword_pr_to_issue", "timestamp(timedelta=0.0, similarity=0.8734165948490467)" ]
8d78893a76a8c14c18b304ffe1fce2dc43ed4206
741602050fbfe555492987b553c6e7023f0e50a1
[ "The problem is pretty simple, it is that we're using `.set(CONNECTION, value)` [here](https://github.com/netty/netty/blob/4.1/codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java#L280) where we should probably be using `.add(CONNECTION, value)`.\r\n\r\nI'll open a PR, and if it turns out I've misunderstood the spec, I'll close it. 😄" ]
[ "You need to release this one", "Also call channel.finish() and assert the return value" ]
"2018-03-30T20:35:47Z"
[ "defect" ]
HttpClientUpgradeHandler may clobber existing connection headers
### Expected behavior `Connection` headers on a request that goes through the `HttpClientUpgradeHandler` should be preserved. ### Actual behavior They are clobbered by the `Connection: Upgrade` header. ### Minimal yet complete reproducer code (or URL to code) Test case for `HttpClientUpgradeHandlerTest`: ```java @Test public void dontStripConnectionHeaders() { HttpClientUpgradeHandler.SourceCodec sourceCodec = new FakeSourceCodec(); HttpClientUpgradeHandler.UpgradeCodec upgradeCodec = new FakeUpgradeCodec(); HttpClientUpgradeHandler handler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 1024); UserEventCatcher catcher = new UserEventCatcher(); EmbeddedChannel channel = new EmbeddedChannel(catcher); channel.pipeline().addFirst("upgrade", handler); DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "netty.io"); request.headers().add("connection", "extra"); request.headers().add("extra", "value"); assertTrue(channel.writeOutbound(request)); FullHttpRequest readRequest = channel.readOutbound(); List<String> connectionHeaders = readRequest.headers().getAll("connection"); assertTrue(connectionHeaders.contains("extra")); } ``` ### Netty version branch 4.1, SHA 5ebee9426f05b0, March 27. ### JVM version (e.g. `java -version`) openjdk version "1.8.0_162" ### OS version (e.g. `uname -a`) Darwin Kernel Version 17.5.0
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpClientUpgradeHandlerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java index 235dbb1b5d8..bf2cd5529ac 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpClientUpgradeHandler.java @@ -277,6 +277,6 @@ private void setUpgradeRequestHeaders(ChannelHandlerContext ctx, HttpRequest req builder.append(','); } builder.append(HttpHeaderValues.UPGRADE); - request.headers().set(HttpHeaderNames.CONNECTION, builder.toString()); + request.headers().add(HttpHeaderNames.CONNECTION, builder.toString()); } }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientUpgradeHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientUpgradeHandlerTest.java index e342ef73e28..a90ee575dd9 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientUpgradeHandlerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpClientUpgradeHandlerTest.java @@ -21,6 +21,7 @@ import java.util.Collection; import java.util.Collections; +import java.util.List; import org.junit.Test; @@ -174,4 +175,25 @@ public void testEarlyBailout() { assertEquals(HttpResponseStatus.OK, response.status()); assertFalse(channel.finish()); } + + @Test + public void dontStripConnectionHeaders() { + HttpClientUpgradeHandler.SourceCodec sourceCodec = new FakeSourceCodec(); + HttpClientUpgradeHandler.UpgradeCodec upgradeCodec = new FakeUpgradeCodec(); + HttpClientUpgradeHandler handler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 1024); + UserEventCatcher catcher = new UserEventCatcher(); + EmbeddedChannel channel = new EmbeddedChannel(catcher); + channel.pipeline().addFirst("upgrade", handler); + + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "netty.io"); + request.headers().add("connection", "extra"); + request.headers().add("extra", "value"); + assertTrue(channel.writeOutbound(request)); + FullHttpRequest readRequest = channel.readOutbound(); + + List<String> connectionHeaders = readRequest.headers().getAll("connection"); + assertTrue(connectionHeaders.contains("extra")); + assertTrue(readRequest.release()); + assertFalse(channel.finish()); + } }
val
val
"2018-03-30T19:32:08"
"2018-03-30T20:23:19Z"
bryce-anderson
val
netty/netty/7829_7834
netty/netty
netty/netty/7829
netty/netty/7834
[ "keyword_pr_to_issue" ]
b02ee1106f81a97334c076e5510d7f90d4f4e224
1fa7a5e697825bdd2f5ad7885b64749ede5c3192
[ "@carl-mastrangelo \r\n> I had assumed the periodic wakeup was some sort of safety net when I saw it. If the intent was to periodically check the scheduledTasks, then yeah, wakeup should probably be the correct mechanism, even if it results in timerfd_settime calls. Arguably there are already a ton of timerfd_settime calls when the group is idle. Doesn't seem all that bad of of a downside to me.\r\n\r\nRight. Your PR https://github.com/netty/netty/pull/7816 will reduce the number of calls for `epoll_wait`, and this change would effectively pull arming the timer outside of the `epoll_wait` call. So the resolution of this issue may result in more calls to `timerfd_settime` after your PR is merged, but compared to the state before your PR my guess is for most use cases it will be a net reduction in `timerfd_settime` calls (in addition to less wakeups when low activity / or no scheduled tasks).\r\n\r\n@normanmaurer \r\n> @Scottmitch that sounds fine to me... That said I think we should be careful and test this carefully :)\r\n\r\n+1. `WriteTask` is an exception to the \"all events that occurs outside the EventLoop do a wake up\". However for the purposes of this issue I don't think it will be too impactful. The worst that may happen is the queue length of the `EventLoop` may grow if there is no flush, and no other event to wakeup the `EventLoop`. This seems unlikely to be an issue because if there is no flush we won't actually write data to the OS, and the writes would sit in the `ChannelOutboundBuffer` queue anyways so the memory consumption should be roughly equivalent.", "I've made an issue touching on wake-ups: #7808 \r\nHow do you think it'l effect that? What do you think about having a thread running with a sleep delay and executing queued runnables so the wakeup bottle neck can be significantly improved?\r\n\r\nThanks,\r\nAJ", "@M-AJ - #7808 doesn't provide the complete context for me to judge if this will have any impact for your use case. However you can try out PR https://github.com/netty/netty/pull/7834 now and let me know 🥇.", "I will try it out tonight and see how it goes!", "What's the maven artifact id for this build?" ]
[ "Can't we just use `Delayed` ?\r\n\r\nhttps://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Delayed.html", "revert", "This should have a `throws` as it may throw a `ClosedChannelException`", "Just use an `AtomicBoolean` as we use it as a boolean.", "We want to get the `deadline`, not the `delay`.", "Good catch (its actually `ChannelException` at the moment).", "I considered this, however it involves additional conditional behind the scenes. Since this is internal I think we can just use `AtomicInteger`.\r\n\r\nI also moved away from the AtomicFieldUpdater because:\r\n- the excepted number of instances for this class is low\r\n- the atomic field updaters have an additional \"instance check\" which can be avoided.", "However this is a runtime exception ... would you prefer a `IOException` using the `errno` like in `epollWait`?", "yeah I think this would be better (using NativeIOException)", "got it", "@Scottmitch that said should we just make this part of the Abstract base class and mark as unstable ? ", "I just went with `IOException` for now ... avoids additional conditional checking and the string description of the error is already included in the `IoExecution` thrown by the JNI code.", "What abstract base class? The issue is we need it to be accessible outside the package (`PromiseTask` and `ScheduledFutureTask` are package private). I considered putting a protected interface in `AbstractScheduledEventExecutor` and can do this to reduce the exposure of this API. I will push this change and we can discuss more if necessary.\r\n\r\nOn a related note ... the relationship between `ScheduledFutureTask` and `AbstractScheduledEventExecutor` is very tightly coupled. I would like to tease these two apart in general as there a assumptions needed about using the \"correct\" `nanoTime` that may be made less \"leaky\" for the next major release (I added something to the doc).", "nit: I think you need to allow negative values here. If you were sorting task based on their delay rather than their deadline, you still need to keep track of which task is most tardy.", "This would be shorter without the or:\r\n\r\n```java\r\n boolean ranAtLeastOneScheduledTask = executeExpiredScheduledTasks(true);\r\n boolean ranAtLeastOneExecutorTask = runExistingTasksFrom(taskQueue);\r\n boolean ranAtLeastOne = ranAtLeastOneScheduledTask || ranAtLeastOneExecutorTask;\r\n```", "I think this would be simpler if you called `size()` up front, and just did a normal for loop until that many tasks were executed. If taskQueue is full, you run the risk of getting an NPE later on.", "This is concerning. I would have expected this to be a non threadsafe queue. If it is threadsafe, that means that it could be concurrently modified. That means that there is race in the code above, where calling `peek` and then `poll` could return different tasks. ", "I agree this could likely be changed, but is pre-existing behavior and doesn't impact this PR. Note that we are sorting, and determining \"next to expire\", based upon deadline (not delay).\r\n\r\nLets discuss in a followup issue: https://github.com/netty/netty/issues/7840", "This is an unbounded MPSC queue and size computation requires an iteration. I think insertion/removal should be a preferred approach here. We can make the assumptions about unbounded queue more clear or be more defensive if that helps.", "> That means that there is race in the code above, where calling peek and then poll could return different tasks.\r\n\r\nThis is operating on a different queue. Here are the queues in play:\r\n- `SingleThreadEventExecutor#taskQueue` - MPSC used for calls to `execute`. This is also currently used by all other transports to put process `schedule` calls on the event loop thread, but this PR changes that behavior for EPOLL.\r\n- `AbstractScheduledEventExecutor#scheduledTaskQueue` - priority queue of scheduled `Runnable`s sorted by deadline. This is NOT thread safe and only touched on the event loop thread.\r\n- `EpollEventLoop#scheduleQueue` - MPSC used to hold `schedule` calls outside of the event loop thread. This is drained when the event loop thread wakes up, and the `Runnable` is appended to `scheduledTaskQueue` (described above).\r\n\r\nThe goal is to decouple the scheduled task queue (`schedule` calls from outside the event loop) from the executor tasks. This allows us to drain all of the scheduled tasks to get an accurate \"next expire time\" before calling `epoll_wait`. In order to ensure we wakeup from outside the event loop we have `nextDeadlineNanos`, which is atomic and indicates the \"next deadline\", and used to know when we should call `setTimerFd` from outside (and inside) the event loop.\r\n\r\nThe class hierarchy and spread of queues is unfortunate, but since EPOLL is the only transport to decouple the `schedule` and `execute` calls I figured best to add `scheduledQueue` here for now.", "Let me add a comment describing this :)", "Actually the queue is unbounded by default, but the user may specify a limit ... let me make this more robust.", "epollWait no longer supports the `-1` special value", "nit: do you even need to memset as you assign all fields anyway", "@Scottmitch maybe I am missing something but is this really correct ? I thought it should be:\r\n\r\n```\r\nreturn !(task instanceof ScheduledTaskRunnable) && super.wakesUpForTask(task);\r\n```\r\n\r\nAt least from what I understand we should never need to wakeup for a `ScheduledTaskRunnable` as the timerfd will take care of it. ", "why this change ? Because it may be able to use XADD ?", "Yes you are correct ... the logic here is flawed 🤦‍♂️ ", "the `it_interval` is not touched below so it is zero'ed out (we don't want a repeating timer).\r\n\r\n```c\r\n struct timespec {\r\n time_t tv_sec; /* Seconds */\r\n long tv_nsec; /* Nanoseconds */\r\n };\r\n\r\n struct itimerspec {\r\n struct timespec it_interval; /* Timer interval */\r\n struct timespec it_value; /* Initial expiration */\r\n };\r\n```", "doh! missed this... good point", "Yes `XADD` also introduced a `AtomicLong` for `nextDeadlineNanos` so I switched this to an `AtomicInteger` because we don't expect many `EventLoop` instances and can avoid the additional checks done by the reference updater. I can revert this portion of the change if you prefer as it isn't critical for this PR. ", "Should we also respect `BOOKEND_TASK ` here, or do we not expect to have one in here as we failed to add it before calling this and only will ever have one in the queue ?", "I am correct to say that we should never have `task == null` here and above ?", "no its fine... just was curious .", "Right. `BOOKEND_TASK` shouldn't be encountered here as you indicated.", " maybe we should add an `assert` ?", "I wouldn't expect this because we don't allow `null` to be offered to the queue, and we only enter this method if we successfully added `BOOKEND_TASK` to the queue. Am I missing something?", "sounds about right... Just wanted to ensure I read it correctly. Maybe an assert would clarify ?", "We can if you prefer however if we don't nothing negative will happen.", "> Maybe an assert would clarify ?\r\n\r\nWe can if you prefer, however if `null` does come up we will NPE and log an error.", "Let us just add a comment... can you do it ?", "Can you just add a comment for it ?", "done", "done", "Missing Javadoc?", "nit: indentation", "Doesn't this method return `false` on removal?", "I'm curious if the parameter type of this method can be widen to `ScheduledTask` or even `Runnable`. If so, we could hide `ScheduledTaskRunnable` (and even `ScheduledTask`) completely from the public API, i.e. less maintenance burden.\r\n\r\nIf a subclass needs the information like deadline, we could just add it as an additional parameter.", "Ditto - can `ScheduledTask` be widen to `Runnable`?", "May be my misunderstanding, but wouldn't ET imply this read _isn't_ needed?", "I was thinking the same as @carl-mastrangelo's [earlier comment](https://github.com/netty/netty/pull/7834#discussion_r178986265) here - that the bookend could be easily avoided by just polling `size()` times. It would be cheaper and simpler, e.g. there's no need to deal specially with the bounded/full case. The JCTools impls won't involve any iteration when called from the consumer.", "Did you ever consider changing to use `TFD_TIMER_ABSTIME`? We could just measure/store the offset of `System.nanoTime()` from the system clock during initialization and then use deadlines rather than delays across the board to further avoid continual absolute/relative conversion.", "I'm not sure that this fully addresses the race condition. I think access to `setTimerFd` probably needs to be synchronized.", "Instead of removing this test why not just adjust it to use the new equivalent `Native.epollWaitNoTimeout` method?", "Replace direct comparison using nanoTime with differences ie ```scheduledTask.deadlineNanos() - nanoTime <= 0```", "Netty's [ScheduledFutureTask offsets all time stamps](https://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java#L34) and they are generally compared using equality for deadlines while giving up half of the domain (e.g. overflow earlier). I agree it is confusing relative to typical use of `System.nanoTime()` and we may want to revisit how time duration/expiration is done in Netty 5 in this area.", "No I didn't consider this.", "good idea! calling from consumer thread for MPSC shouldn't require looping.", "\"earlier\" being after only 300 years, rather than 600 :)", "The way this suggestion was implemented makes things more complex IMHO. We are trying to communicate from here that the type of task is for scheduled execution, and this information is used conditionally at higher layers (e.g. should we wake up). This has been changed to introduce 3 methods (e.g. `beforeScheduledTaskSubmitted`, `afterScheduledTaskSubmitted`, `wakesUpForScheduledRunnable`) and 1 additional type is exposed `NonWakeupRunnable` publicly which may require conditional allocation/wrapping at higher layers. IOW we are losing information by just allocating a `Runnable` here and have to compensate by complicating method signatures and type hierarchy at other layers.\r\n\r\nI'll submit a followup PR (since this plus an additional PR was recently reverted) so we can take a look. /cc @normanmaurer @njhill ", "Thanks @Scottmitch. I gave this quite a lot of thought so would be good to discuss more. A few initial responses though:\r\n- The prior communication depended on the notion of an intermediate task which happens to involve enqueing some other scheduled task onto the internal scheduled-task queue (i.e. not the scheduled task itself), which is something we should not be exposing at all imho... that seems like an internal detail which EL impls shouldn't be aware of.\r\n- I don't see `wakesUpForScheduledRunnable` that you referenced, do you mean `wakesUpForRunnable` or `executeScheduledRunnable`?\r\n- The only reason I left `wakesUpForRunnable` there is that it's protected and so would be a breaking change to remove it, I'd suggest that we deprecate it. A public `NonWakeupRunnable` interface serves a similar purpose but makes much more sense imho. Whether a given task is required to be run immediately is in general a property of that task and should be independent of the executor/EL implementation. We could consider a `lazyExecute(Runnable)` method in addition to this (might be be nice to have on the `EventExecutor` interface in netty 5).\r\n- I actually think we should remove `executeScheduledRunnable` altogether (possible since it's package-private), and instead just override `schedule(...)` in `SingleThreadEventExecutor`. This would further simplify things and avoid the double `Runnable` wrapping. Not sure it's also what you had in mind but it's a small change, I'll also push an example of that\r\n- Only the changes to `EpollEventLoop` itself were reverted for the release, the reworked superclass abstractions are still there. I'm still very interested to find out what the issues were ... @normanmaurer any luck with a reproducer or more clues? :)", "@Scottmitch I made the changes alluded to above here 3923176afebefe58bf85155d25ed10962f9dd660 but took things a bit further still, uplifting the before/after hooks to `AbstractScheduledEventExecutor` and introducing higher level idea of `lazyExecute` / `LazyRunnable` which could have general applicability.\r\n\r\nI really think this is both simpler to exploit and more generally useful for subclasses (i.e. event loop impls). " ]
"2018-04-03T03:02:40Z"
[ "improvement" ]
Improve Timer Wakeup for Native Transports
from https://github.com/netty/netty/pull/7816#discussion_r178171275 This topic comes up in frequently enough that I usually forget the answer .... "why do we need to have a max wakeup time of 1 second instead of unbounded" for the EventLoop implementations. IIRC the answer is when we schedule tasks we don't check if the new time results in a sooner deadline than the previous wakeup on the EventLoop. I think I investigated other events from outside the EventLoop and they should be invoking `wakeup` (and we have an atomic boolean protecting wakeup to avoid too many system calls). I wonder if now that we are saving the `prevDeadlineNanos`, and we have a timer mechanism independent of `epoll_wait`, if we can avoid waking up every second (and additional `timerfd_settime` system calls), and instead only wakeup when necessary. Potential benefits: - if there are no scheduled task, we only wakeup when I/O occurs - we will be more responsive to schedule tasks (because we can adjust the wakeup to the minimum delay as new tasks are scheduled) Potential negatives: - in the degenerate case if someone schedules tasks in decreasing order of expiration (10 seconds from now, 9 seconds, 8 seconds, etc...) we will have to touch the the `timerfd_settime` on each schedule. For outside the EventLoop we wouldn't have to wakeup the `epoll_wait` call (assuming `timerfd_settime` is thread safe). @normanmaurer @carl-mastrangelo - wdyt? We could do the same thing for kqueue too (we would need to use a timerfd equivalent there too though).
[ "common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java", "common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java", "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java", "transport-native-epoll/src/main/c/netty_epoll_native.c", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java", "transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java" ]
[ "common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java", "common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java", "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java", "transport-native-epoll/src/main/c/netty_epoll_native.c", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java", "transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java index 41430c708c3..6b52151dbfa 100644 --- a/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/AbstractScheduledEventExecutor.java @@ -29,7 +29,6 @@ * Abstract base class for {@link EventExecutor}s that want to support scheduling. */ public abstract class AbstractScheduledEventExecutor extends AbstractEventExecutor { - private static final Comparator<ScheduledFutureTask<?>> SCHEDULED_FUTURE_TASK_COMPARATOR = new Comparator<ScheduledFutureTask<?>>() { @Override @@ -51,6 +50,24 @@ protected static long nanoTime() { return ScheduledFutureTask.nanoTime(); } + /** + * Given an arbitrary deadline {@code deadlineNanos}, calculate the number of nano seconds from now + * {@code deadlineNanos} would expire. + * @param deadlineNanos An arbitrary deadline in nano seconds. + * @return the number of nano seconds from now {@code deadlineNanos} would expire. + */ + protected static long deadlineToDelayNanos(long deadlineNanos) { + return ScheduledFutureTask.deadlineToDelayNanos(deadlineNanos); + } + + /** + * The initial value used for delay and computations based upon a monatomic time source. + * @return initial value used for delay and computations based upon a monatomic time source. + */ + protected static long initialNanoTime() { + return ScheduledFutureTask.initialNanoTime(); + } + PriorityQueue<ScheduledFutureTask<?>> scheduledTaskQueue() { if (scheduledTaskQueue == null) { scheduledTaskQueue = new DefaultPriorityQueue<ScheduledFutureTask<?>>( @@ -85,6 +102,10 @@ protected void cancelScheduledTasks() { } scheduledTaskQueue.clearIgnoringIndexes(); + + // calling minimumDelayScheduledTaskRemoved was considered here to give a chance for EventLoop + // implementations the opportunity to cleanup any timerFds, but this is currently only called when the EventLoop + // is being shutdown, so the timerFd and associated polling mechanism will be destroyed anyways. } /** @@ -99,16 +120,21 @@ protected final Runnable pollScheduledTask() { * You should use {@link #nanoTime()} to retrieve the correct {@code nanoTime}. */ protected final Runnable pollScheduledTask(long nanoTime) { - assert inEventLoop(); - Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; - ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); - if (scheduledTask == null) { - return null; - } + return scheduledTaskQueue != null ? pollScheduledTask(scheduledTaskQueue, nanoTime, true) : null; + } + + final Runnable pollScheduledTask(Queue<ScheduledFutureTask<?>> scheduledTaskQueue, long nanoTime, + boolean notifyMinimumDeadlineRemoved) { + assert scheduledTaskQueue != null; + assert inEventLoop(); - if (scheduledTask.deadlineNanos() <= nanoTime) { - scheduledTaskQueue.remove(); + ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue.peek(); + if (scheduledTask != null && scheduledTask.deadlineNanos() <= nanoTime) { + scheduledTaskQueue.poll(); + if (notifyMinimumDeadlineRemoved) { + minimumDelayScheduledTaskRemoved(scheduledTask, scheduledTask.deadlineNanos()); + } return scheduledTask; } return null; @@ -118,28 +144,29 @@ protected final Runnable pollScheduledTask(long nanoTime) { * Return the nanoseconds when the next scheduled task is ready to be run or {@code -1} if no task is scheduled. */ protected final long nextScheduledTaskNano() { - Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; - ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); - if (scheduledTask == null) { - return -1; - } - return Math.max(0, scheduledTask.deadlineNanos() - nanoTime()); + ScheduledFutureTask<?> scheduledTask = peekScheduledTask(); + return scheduledTask != null ? Math.max(0, scheduledTask.deadlineNanos() - nanoTime()) : -1; + } + + /** + * Return the deadline (in nanoseconds) when the next scheduled task is ready to be run or {@code -1} + * if no task is scheduled. + */ + protected final long nextScheduledTaskDeadlineNanos() { + ScheduledFutureTask<?> scheduledTask = peekScheduledTask(); + return scheduledTask != null ? scheduledTask.deadlineNanos() : -1; } final ScheduledFutureTask<?> peekScheduledTask() { Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; - if (scheduledTaskQueue == null) { - return null; - } - return scheduledTaskQueue.peek(); + return scheduledTaskQueue != null ? scheduledTaskQueue.peek() : null; } /** * Returns {@code true} if a scheduled task is ready for processing. */ protected final boolean hasScheduledTasks() { - Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue; - ScheduledFutureTask<?> scheduledTask = scheduledTaskQueue == null ? null : scheduledTaskQueue.peek(); + ScheduledFutureTask<?> scheduledTask = peekScheduledTask(); return scheduledTask != null && scheduledTask.deadlineNanos() <= nanoTime(); } @@ -225,16 +252,16 @@ protected void validateScheduled(long amount, TimeUnit unit) { // NOOP } - <V> ScheduledFuture<V> schedule(final ScheduledFutureTask<V> task) { + private <V> ScheduledFuture<V> schedule(final ScheduledFutureTask<V> task) { if (inEventLoop()) { scheduledTaskQueue().add(task); } else { - execute(new Runnable() { + executeScheduledRunnable(new Runnable() { @Override public void run() { scheduledTaskQueue().add(task); } - }); + }, true, task.deadlineNanos()); } return task; @@ -242,14 +269,48 @@ public void run() { final void removeScheduled(final ScheduledFutureTask<?> task) { if (inEventLoop()) { - scheduledTaskQueue().removeTyped(task); + removedSchedule0(task); } else { - execute(new Runnable() { + executeScheduledRunnable(new Runnable() { @Override public void run() { - removeScheduled(task); + removedSchedule0(task); } - }); + }, false, task.deadlineNanos()); } } + + private void removedSchedule0(final ScheduledFutureTask<?> task) { + if (scheduledTaskQueue == null || task == null) { + return; + } + if (scheduledTaskQueue.peek() == task) { + scheduledTaskQueue.poll(); + minimumDelayScheduledTaskRemoved(task, task.deadlineNanos()); + } else { + scheduledTaskQueue.removeTyped(task); + } + } + + /** + * Execute a {@link Runnable} from outside the event loop thread that is responsible for adding or removing + * a scheduled action. Note that schedule events which occur on the event loop thread do not interact with this + * method. + * @param runnable The {@link Runnable} to execute which will add or remove a scheduled action + * @param isAddition {@code true} if the {@link Runnable} will add an action, {@code false} if it will remove an + * action + * @param deadlineNanos the deadline in nanos of the scheduled task that will be added or removed. + */ + protected void executeScheduledRunnable(Runnable runnable, + @SuppressWarnings("unused") boolean isAddition, + @SuppressWarnings("unused") long deadlineNanos) { + execute(runnable); + } + + /** + * The next task to expire (e.g. minimum delay) has been removed from the scheduled priority queue. + */ + protected void minimumDelayScheduledTaskRemoved(@SuppressWarnings("unused") Runnable task, + @SuppressWarnings("unused") long deadlineNanos) { + } } diff --git a/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java b/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java index 1eaa7b92762..1d1403e3f0c 100644 --- a/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java +++ b/common/src/main/java/io/netty/util/concurrent/ScheduledFutureTask.java @@ -40,6 +40,10 @@ static long deadlineNanos(long delay) { return deadlineNanos < 0 ? Long.MAX_VALUE : deadlineNanos; } + static long initialNanoTime() { + return START_TIME; + } + private final long id = nextTaskId.getAndIncrement(); private long deadlineNanos; /* 0 - no repeat, >0 - repeat at fixed rate, <0 - repeat with fixed delay */ @@ -85,7 +89,11 @@ public long deadlineNanos() { } public long delayNanos() { - return Math.max(0, deadlineNanos() - nanoTime()); + return deadlineToDelayNanos(deadlineNanos()); + } + + static long deadlineToDelayNanos(long deadlineNanos) { + return Math.max(0, deadlineNanos - nanoTime()); } public long delayNanos(long currentTimeNanos) { @@ -111,9 +119,8 @@ public int compareTo(Delayed o) { return 1; } else if (id < that.id) { return -1; - } else if (id == that.id) { - throw new Error(); } else { + assert id != that.id; return 1; } } @@ -132,11 +139,10 @@ public void run() { if (!isCancelled()) { task.call(); if (!executor().isShutdown()) { - long p = periodNanos; - if (p > 0) { - deadlineNanos += p; + if (periodNanos > 0) { + deadlineNanos += periodNanos; } else { - deadlineNanos = nanoTime() - p; + deadlineNanos = nanoTime() - periodNanos; } if (!isCancelled()) { // scheduledTaskQueue can never be null as we lazy init it before submit the task! diff --git a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java index a7aee9a4c6b..cf635f72162 100644 --- a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -73,6 +73,12 @@ public void run() { // Do nothing. } }; + private static final Runnable BOOKEND_TASK = new Runnable() { + @Override + public void run() { + // Do nothing. + } + }; private static final AtomicIntegerFieldUpdater<SingleThreadEventExecutor> STATE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "state"); @@ -283,19 +289,41 @@ protected Runnable takeTask() { } private boolean fetchFromScheduledTaskQueue() { + if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { + return true; + } long nanoTime = AbstractScheduledEventExecutor.nanoTime(); - Runnable scheduledTask = pollScheduledTask(nanoTime); + Runnable scheduledTask = pollScheduledTask(scheduledTaskQueue, nanoTime, true); while (scheduledTask != null) { if (!taskQueue.offer(scheduledTask)) { // No space left in the task queue add it back to the scheduledTaskQueue so we pick it up again. - scheduledTaskQueue().add((ScheduledFutureTask<?>) scheduledTask); + scheduledTaskQueue.add((ScheduledFutureTask<?>) scheduledTask); return false; } - scheduledTask = pollScheduledTask(nanoTime); + scheduledTask = pollScheduledTask(scheduledTaskQueue, nanoTime, false); } return true; } + /** + * @return {@code true} if at least one scheduled task was executed. + */ + private boolean executeExpiredScheduledTasks(boolean notifyMinimumDeadlineRemoved) { + if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) { + return false; + } + long nanoTime = AbstractScheduledEventExecutor.nanoTime(); + Runnable scheduledTask = pollScheduledTask(scheduledTaskQueue, nanoTime, notifyMinimumDeadlineRemoved); + if (scheduledTask != null) { + do { + safeExecute(scheduledTask); + scheduledTask = pollScheduledTask(scheduledTaskQueue, nanoTime, false); + } while (scheduledTask != null); + return true; + } + return false; + } + /** * @see Queue#peek() */ @@ -376,6 +404,36 @@ protected boolean runAllTasks() { return ranAtLeastOne; } + /** + * Execute all expired scheduled tasks and all current tasks in the executor queue until both queues are empty, + * or {@code maxDrainAttempts} has been exceeded. + * @param maxDrainAttempts The maximum amount of times this method attempts to drain from queues. This is to prevent + * continuous task execution and scheduling from preventing the EventExecutor thread to + * make progress and return to the selector mechanism to process inbound I/O events. + * @return {@code true} if at least one task was run. + */ + protected final boolean runScheduledAndExecutorTasks(final int maxDrainAttempts) { + assert inEventLoop(); + // We must run the taskQueue tasks first, because the scheduled tasks from outside the EventLoop are queued + // here because the taskQueue is thread safe and the scheduledTaskQueue is not thread safe. + boolean ranAtLeastOneExecutorTask = runExistingTasksFrom(taskQueue); + boolean ranAtLeastOneScheduledTask = executeExpiredScheduledTasks(true); + int drainAttempt = 0; + while ((ranAtLeastOneExecutorTask || ranAtLeastOneScheduledTask) && ++drainAttempt < maxDrainAttempts) { + // We must run the taskQueue tasks first, because the scheduled tasks from outside the EventLoop are queued + // here because the taskQueue is thread safe and the scheduledTaskQueue is not thread safe. + ranAtLeastOneExecutorTask = runExistingTasksFrom(taskQueue); + ranAtLeastOneScheduledTask = executeExpiredScheduledTasks(false); + } + + if (drainAttempt > 0) { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + } + afterRunningAllTasks(); + + return drainAttempt > 0; + } + /** * Runs all tasks from the passed {@code taskQueue}. * @@ -397,6 +455,55 @@ protected final boolean runAllTasksFrom(Queue<Runnable> taskQueue) { } } + /** + * What ever tasks are present in {@code taskQueue} when this method is invoked will be {@link Runnable#run()}. + * @param taskQueue the task queue to drain. + * @return {@code true} if at least {@link Runnable#run()} was called. + */ + private boolean runExistingTasksFrom(Queue<Runnable> taskQueue) { + return taskQueue.offer(BOOKEND_TASK) ? runExistingTasksUntilBookend(taskQueue) + : runExistingTasksUntilMaxTasks(taskQueue); + } + + private boolean runExistingTasksUntilBookend(Queue<Runnable> taskQueue) { + Runnable task = pollTaskFrom(taskQueue); + // null is not expected because this method isn't called unless BOOKEND_TASK was inserted into the queue, and + // null elements are not permitted to be inserted into the queue. + if (task == BOOKEND_TASK) { + return false; + } + for (;;) { + safeExecute(task); + task = pollTaskFrom(taskQueue); + // null is not expected because this method isn't called unless BOOKEND_TASK was inserted into the queue, + // and null elements are not permitted to be inserted into the queue. + if (task == BOOKEND_TASK) { + return true; + } + } + } + + private boolean runExistingTasksUntilMaxTasks(Queue<Runnable> taskQueue) { + Runnable task = pollTaskFrom(taskQueue); + // BOOKEND_TASK is not expected because this method isn't called unless BOOKEND_TASK fails to be inserted into + // the queue, and if was previously inserted we always drain all the elements from queue including BOOKEND_TASK. + if (task == null) { + return false; + } + int i = 0; + do { + safeExecute(task); + task = pollTaskFrom(taskQueue); + // BOOKEND_TASK is not expected because this method isn't called unless BOOKEND_TASK fails to be inserted + // into the queue, and if was previously inserted we always drain all the elements from queue including + // BOOKEND_TASK. + if (task == null) { + return true; + } + } while (++i < maxPendingTasks); + return true; + } + /** * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. This method stops running * the tasks in the task queue and returns if it ran longer than {@code timeoutNanos}. @@ -443,6 +550,7 @@ protected boolean runAllTasks(long timeoutNanos) { */ @UnstableApi protected void afterRunningAllTasks() { } + /** * Returns the amount of time left until the scheduled task with the closest dead line is executed. */ @@ -846,8 +954,7 @@ public final ThreadProperties threadProperties() { return threadProperties; } - @SuppressWarnings("unused") - protected boolean wakesUpForTask(Runnable task) { + protected boolean wakesUpForTask(@SuppressWarnings("unused") Runnable task) { return true; } diff --git a/transport-native-epoll/src/main/c/netty_epoll_native.c b/transport-native-epoll/src/main/c/netty_epoll_native.c index f754a3e4627..264875dc65b 100644 --- a/transport-native-epoll/src/main/c/netty_epoll_native.c +++ b/transport-native-epoll/src/main/c/netty_epoll_native.c @@ -186,6 +186,31 @@ static jint netty_epoll_native_epollCreate(JNIEnv* env, jclass clazz) { return efd; } +static void netty_epoll_native_timerFdSetTime(JNIEnv* env, jclass clazz, jint timerFd, jint tvSec, jint tvNsec) { + struct itimerspec ts; + memset(&ts.it_interval, 0, sizeof(struct timespec)); + ts.it_value.tv_sec = tvSec; + ts.it_value.tv_nsec = tvNsec; + if (timerfd_settime(timerFd, 0, &ts, NULL) < 0) { + netty_unix_errors_throwIOExceptionErrorNo(env, "timerfd_settime() failed: ", errno); + } +} + +static jint netty_epoll_native_epollWaitNoTimeout(JNIEnv* env, jclass clazz, jint efd, jlong address, jint len, jboolean immediatePoll) { + struct epoll_event *ev = (struct epoll_event*) (intptr_t) address; + const int timeout = immediatePoll ? 0 : -1; + int result, err; + + do { + result = epoll_wait(efd, ev, len, timeout); + if (result >= 0) { + return result; + } + } while((err = errno) == EINTR); + return -err; +} + +// This method is deprecated! static jint netty_epoll_native_epollWait0(JNIEnv* env, jclass clazz, jint efd, jlong address, jint len, jint timerFd, jint tvSec, jint tvNsec) { struct epoll_event *ev = (struct epoll_event*) (intptr_t) address; int result, err; @@ -429,8 +454,10 @@ static const JNINativeMethod fixed_method_table[] = { { "eventFdWrite", "(IJ)V", (void *) netty_epoll_native_eventFdWrite }, { "eventFdRead", "(I)V", (void *) netty_epoll_native_eventFdRead }, { "timerFdRead", "(I)V", (void *) netty_epoll_native_timerFdRead }, + { "timerFdSetTime", "(III)V", (void *) netty_epoll_native_timerFdSetTime }, { "epollCreate", "()I", (void *) netty_epoll_native_epollCreate }, - { "epollWait0", "(IJIIII)I", (void *) netty_epoll_native_epollWait0 }, + { "epollWait0", "(IJIIII)I", (void *) netty_epoll_native_epollWait0 }, // This method is deprecated! + { "epollWaitNoTimeout", "(IJIZ)I", (void *) netty_epoll_native_epollWaitNoTimeout }, { "epollBusyWait0", "(IJI)I", (void *) netty_epoll_native_epollBusyWait0 }, { "epollCtlAdd0", "(III)I", (void *) netty_epoll_native_epollCtlAdd0 }, { "epollCtlMod0", "(III)I", (void *) netty_epoll_native_epollCtlMod0 }, diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java index 27bc1d1065d..e6ac6c66e37 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoop.java @@ -35,7 +35,9 @@ import java.io.IOException; import java.util.Queue; import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import static java.lang.Math.min; @@ -44,8 +46,10 @@ */ class EpollEventLoop extends SingleThreadEventLoop { private static final InternalLogger logger = InternalLoggerFactory.getInstance(EpollEventLoop.class); - private static final AtomicIntegerFieldUpdater<EpollEventLoop> WAKEN_UP_UPDATER = - AtomicIntegerFieldUpdater.newUpdater(EpollEventLoop.class, "wakenUp"); + /** + * The maximum deadline value before overlap occurs on the time source. + */ + private static final long MAXIMUM_DEADLINE = initialNanoTime() - 1; static { // Ensure JNI is initialized by the time this class is loaded by this time! @@ -53,8 +57,12 @@ class EpollEventLoop extends SingleThreadEventLoop { Epoll.ensureAvailability(); } - // Pick a number that no task could have previously used. - private long prevDeadlineNanos = nanoTime() - 1; + /** + * Note that we use deadline instead of delay because deadline is just a fixed number but delay requires interacting + * with the time source (e.g. calling System.nanoTime()) which can be expensive. + */ + private final AtomicLong nextDeadlineNanos = new AtomicLong(MAXIMUM_DEADLINE); + private final AtomicInteger wakenUp = new AtomicInteger(); private final FileDescriptor epollFd; private final FileDescriptor eventFd; private final FileDescriptor timerFd; @@ -73,12 +81,6 @@ public int get() throws Exception { return epollWaitNow(); } }; - @SuppressWarnings("unused") // AtomicIntegerFieldUpdater - private volatile int wakenUp; - private volatile int ioRatio = 50; - - // See http://man7.org/linux/man-pages/man2/timerfd_create.2.html. - private static final long MAX_SCHEDULED_TIMERFD_NS = 999999999; EpollEventLoop(EventLoopGroup parent, Executor executor, int maxEvents, SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler, @@ -175,9 +177,112 @@ NativeDatagramPacketArray cleanDatagramPacketArray() { return datagramPacketArray; } + @Override + protected void executeScheduledRunnable(Runnable runnable, boolean isAddition, long deadlineNanos) { + if (isAddition) { + try { + trySetTimerFd(deadlineNanos); + } catch (IOException cause) { + throw new RejectedExecutionException(cause); + } + } + // else this is a removal of scheduled task and we could attempt to detect if this task was responsible + // for the next delay, and find the next lowest delay in the queue to re-set the timer. However this + // is not practical for the following reasons: + // 1. The data structure is a PriorityQueue, and the scheduled task has not yet been removed. This means + // we would have to add/remove the head element to find the "next timeout". + // 2. We are not on the EventLoop thread, and the PriorityQueue is not thread safe. We could attempt + // to do (1) if we are on the EventLoop but when the EventLoop wakes up it checks if the timeout changes + // when it is woken up and before it calls epoll_wait again and adjusts the timer accordingly. + // The result is we wait until we are in the EventLoop and doing the actual removal, and also processing + // regular polling in the EventLoop too. + + execute(runnable); + } + + @Override + protected boolean wakesUpForScheduledRunnable() { + return false; + } + + @Override + protected boolean runAllTasks() { + // This method is overridden to ensure that all the expired scheduled tasks are executed during shutdown, and + // any other execute all scenarios in the base class. + return runScheduledAndExecutorTasks(4); + } + + private void trySetTimerFd(long candidateNextDeadline) throws IOException { + for (;;) { + long nextDeadline = nextDeadlineNanos.get(); + if (nextDeadline - candidateNextDeadline <= 0) { + break; + } + if (nextDeadlineNanos.compareAndSet(nextDeadline, candidateNextDeadline)) { + setTimerFd(deadlineToDelayNanos(candidateNextDeadline)); + // We are setting the timerFd outside of the EventLoop so it is possible that we raced with another call + // to set the timer and temporarily increased the value, in which case we should set it back to the + // lower value. + nextDeadline = nextDeadlineNanos.get(); + if (nextDeadline - candidateNextDeadline < 0) { + setTimerFd(deadlineToDelayNanos(nextDeadline)); + } + break; + } + } + } + + private void setTimerFd(long candidateNextDelayNanos) throws IOException { + if (candidateNextDelayNanos > 0) { + final int delaySeconds = (int) min(candidateNextDelayNanos / 1000000000L, Integer.MAX_VALUE); + final int delayNanos = (int) min(candidateNextDelayNanos - delaySeconds * 1000000000L, Integer.MAX_VALUE); + Native.timerFdSetTime(timerFd.intValue(), delaySeconds, delayNanos); + } else { + // Setting the timer to 0, 0 will disarm it, so we have a few options: + // 1. Set the timer wakeup to 1ns (1 system call). + // 2. Use the eventFd to force a wakeup and disarm the timer (2 system calls). + // For now we are using option (1) because there are less system calls, and we will correctly reset the + // nextDeadlineNanos state when the EventLoop processes the timer wakeup. + Native.timerFdSetTime(timerFd.intValue(), 0, 1); + } + } + + private void checkScheduleTaskQueueForNewDelay() throws IOException { + final long deadlineNanos = nextScheduledTaskDeadlineNanos(); + if (deadlineNanos != -1) { + trySetTimerFd(deadlineNanos); + } + // Don't disarm the timerFd even if there are no more queued tasks. Since we are setting timerFd from outside + // the EventLoop it is possible that another thread has set the timer and we may miss a wakeup if we disarm + // the timer here. Instead we wait for the timer wakeup on the EventLoop and clear state for the next timer. + } + + @Override + protected void minimumDelayScheduledTaskRemoved(@SuppressWarnings("unused") Runnable task, + @SuppressWarnings("unused") long deadlineNanos) { + // It is OK to reset nextDeadlineNanos here because we are in the event loop thread, and the event loop is + // guaranteed to transfer all pending ScheduledFutureTasks from the executor queue to the scheduled + // PriorityQueue and we will set the next expiration time. If another thread races with this thread inserting a + // ScheduledFutureTasks into the executor queue it should be OK, assuming the executor queue insertion is + // visible to the event loop thread. + // + // Assume the current minimum timer is delayNanos = 10 + // Thread A -> execute(ScheduledFutureTask(delayNanos = 12)), + // add ScheduledFutureTask to the executor queue + // fail to set nextDeadlineNanos, so no call to setTimerFd is made + // EventLoop -> minimumDelayScheduledTaskRemoved(10), + // set nextDeadlineNanos to MAXIMUM_DEADLINE + // ... process more tasks ... + // drain all the tasks from the executor queue, see that 12 is the next delay, call setTimerFd + nextDeadlineNanos.set(MAXIMUM_DEADLINE); + + // Note that we don't actually call setTimerFd here, we don't want to interrupt the actual timerFd and let + // the end of the EventLoop determine what the timerFd value should be (after execute queue is drained). + } + @Override protected void wakeup(boolean inEventLoop) { - if (!inEventLoop && WAKEN_UP_UPDATER.getAndSet(this, 1) == 0) { + if (!inEventLoop && wakenUp.getAndSet(1) == 0) { // write to the evfd which will then wake-up epoll_wait(...) Native.eventFdWrite(eventFd.intValue(), 1L); } @@ -237,47 +342,21 @@ private static Queue<Runnable> newTaskQueue0(int maxPendingTasks) { : PlatformDependent.<Runnable>newMpscQueue(maxPendingTasks); } - /** - * Returns the percentage of the desired amount of time spent for I/O in the event loop. - */ - public int getIoRatio() { - return ioRatio; - } - - /** - * Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is - * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. - */ - public void setIoRatio(int ioRatio) { - if (ioRatio <= 0 || ioRatio > 100) { - throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); - } - this.ioRatio = ioRatio; - } - @Override public int registeredChannels() { return channels.size(); } private int epollWait() throws IOException { - int delaySeconds; - int delayNanos; - long curDeadlineNanos = deadlineNanos(); - if (curDeadlineNanos == prevDeadlineNanos) { - delaySeconds = -1; - delayNanos = -1; - } else { - long totalDelay = delayNanos(System.nanoTime()); - prevDeadlineNanos = curDeadlineNanos; - delaySeconds = (int) min(totalDelay / 1000000000L, Integer.MAX_VALUE); - delayNanos = (int) min(totalDelay - delaySeconds * 1000000000L, MAX_SCHEDULED_TIMERFD_NS); - } - return Native.epollWait(epollFd, events, timerFd, delaySeconds, delayNanos); + // If a task was submitted when wakenUp value was 1, the task didn't get a chance to produce wakeup event. + // So we need to check task queue again before calling epoll_wait. If we don't, the task might be pended + // until epoll_wait was timed out. It might be pended until idle timeout if IdleStateHandler existed + // in pipeline. + return Native.epollWait(epollFd, events, hasTasks()); } private int epollWaitNow() throws IOException { - return Native.epollWait(epollFd, events, timerFd, 0, 0); + return Native.epollWait(epollFd, events, true); } private int epollBusyWait() throws IOException { @@ -298,8 +377,8 @@ protected void run() { break; case SelectStrategy.SELECT: - if (wakenUp == 1) { - wakenUp = 0; + if (wakenUp.get() == 1) { + wakenUp.set(0); } if (!hasTasks()) { strategy = epollWait(); @@ -308,27 +387,21 @@ protected void run() { default: } - final int ioRatio = this.ioRatio; - if (ioRatio == 100) { + try { + processReady(events, strategy); + } finally { try { - if (strategy > 0) { - processReady(events, strategy); - } - } finally { - // Ensure we always run tasks. + // Note the timerFd code depends upon running all the tasks on each event loop run. This is so + // we can get an accurate "next wakeup time" after the event loop run completes. runAllTasks(); - } - } else { - final long ioStartTime = System.nanoTime(); - - try { - if (strategy > 0) { - processReady(events, strategy); - } } finally { - // Ensure we always run tasks. - final long ioTime = System.nanoTime() - ioStartTime; - runAllTasks(ioTime * (100 - ioRatio) / ioRatio); + // No need to drainScheduledQueue() after the fact, because all in event loop scheduling results + // in direct addition to the scheduled priority queue. + + // When we are in the EventLoop we don't bother setting the timerFd for each scheduled task, but + // instead defer the processing until the end of the EventLoop to reduce the timerFd + // modifications. + checkScheduleTaskQueueForNewDelay(); } } if (allowGrowing && strategy == events.length()) { @@ -384,12 +457,34 @@ private void closeAll() { } private void processReady(EpollEventArray events, int ready) { - for (int i = 0; i < ready; i ++) { + for (int i = 0; i < ready; ++i) { final int fd = events.fd(i); - if (fd == eventFd.intValue() || fd == timerFd.intValue()) { + if (fd == eventFd.intValue()) { // Just ignore as we use ET mode for the eventfd and timerfd. // // See also https://stackoverflow.com/a/12492308/1074097 + } else if (fd == timerFd.intValue()) { + // consume wakeup event, necessary because the timer is added with ET mode. + Native.timerFdRead(fd); + + // The timer is normalized, monotonically increasing, and the next value is always set to the minimum + // value of the pending timers. When the timer fires we can unset the timer value. + // Worst case another thread races with this thread and we set another timer event while processing + // this timer event and we get a duplicate wakeup some time in the future. + // + // This works because we always drain all ScheduledFutureTasks from the executor queue to the scheduled + // PriorityQueue and we will set the next expiration time. If another thread races with this thread + // inserting a ScheduledFutureTasks into the executor queue it should be OK, assuming the executor queue + // insertion is visible to the event loop thread. + // + // Assume the current minimum timer is nextDeadlineNanos = 10 + // Thread A -> execute(ScheduledFutureTask(delayNanos = 12)), + // add ScheduledFutureTask to the executor queue + // fail to set nextDeadlineNanos, so no call to setTimerFd is made + // EventLoop -> process timer wakeup here, set nextDeadlineNanos to MAXIMUM_DEADLINE + // ... process more tasks ... + // drain all the tasks from executor queue, see 12 is the next delay, call setTimerFd + nextDeadlineNanos.set(MAXIMUM_DEADLINE); } else { final long ev = events.events(i); diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java index 85c5d5c158a..4047fb72440 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollEventLoopGroup.java @@ -21,7 +21,6 @@ import io.netty.channel.EventLoopTaskQueueFactory; import io.netty.channel.MultithreadEventLoopGroup; import io.netty.channel.SelectStrategyFactory; -import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.EventExecutorChooserFactory; import io.netty.util.concurrent.RejectedExecutionHandler; import io.netty.util.concurrent.RejectedExecutionHandlers; @@ -128,12 +127,12 @@ public EpollEventLoopGroup(int nThreads, Executor executor, EventExecutorChooser } /** - * Sets the percentage of the desired amount of time spent for I/O in the child event loops. The default value is - * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. + * @deprecated This method will be removed in future releases, and is not guaranteed to have any impacts. */ + @Deprecated public void setIoRatio(int ioRatio) { - for (EventExecutor e: this) { - ((EpollEventLoop) e).setIoRatio(ioRatio); + if (ioRatio <= 0 || ioRatio > 100) { + throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); } } diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java index fed3e81e5e5..b8d17f011a0 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/Native.java @@ -84,6 +84,7 @@ public static FileDescriptor newTimerFd() { public static native void eventFdWrite(int fd, long value); public static native void eventFdRead(int fd); static native void timerFdRead(int fd); + static native void timerFdSetTime(int fd, int sec, int nsec) throws IOException; public static FileDescriptor newEpollCreate() { return new FileDescriptor(epollCreate()); @@ -91,6 +92,10 @@ public static FileDescriptor newEpollCreate() { private static native int epollCreate(); + /** + * @deprecated this method is no longer supported. This functionality is internal to this package. + */ + @Deprecated public static int epollWait(FileDescriptor epollFd, EpollEventArray events, FileDescriptor timerFd, int timeoutSec, int timeoutNs) throws IOException { int ready = epollWait0(epollFd.intValue(), events.memoryAddress(), events.length(), timerFd.intValue(), @@ -100,7 +105,14 @@ public static int epollWait(FileDescriptor epollFd, EpollEventArray events, File } return ready; } - private static native int epollWait0(int efd, long address, int len, int timerFd, int timeoutSec, int timeoutNs); + + static int epollWait(FileDescriptor epollFd, EpollEventArray events, boolean immediatePoll) throws IOException { + int ready = epollWaitNoTimeout(epollFd.intValue(), events.memoryAddress(), events.length(), immediatePoll); + if (ready < 0) { + throw newIOException("epoll_wait", ready); + } + return ready; + } /** * Non-blocking variant of @@ -115,6 +127,8 @@ public static int epollBusyWait(FileDescriptor epollFd, EpollEventArray events) return ready; } + private static native int epollWait0(int efd, long address, int len, int timerFd, int timeoutSec, int timeoutNs); + private static native int epollWaitNoTimeout(int efd, long address, int len, boolean immediatePoll); private static native int epollBusyWait0(int efd, long address, int len); public static void epollCtlAdd(int efd, final int fd, final int flags) throws IOException { diff --git a/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java b/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java index 9abb39fc389..7eff9e85fab 100644 --- a/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java +++ b/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java @@ -102,6 +102,20 @@ public ChannelFuture register(final Channel channel, final ChannelPromise promis return promise; } + @Override + protected void executeScheduledRunnable(final Runnable runnable, boolean isAddition, long deadlineNanos) { + super.executeScheduledRunnable(wakesUpForScheduledRunnable() ? runnable : new NonWakeupRunnable() { + @Override + public void run() { + runnable.run(); + } + }, isAddition, deadlineNanos); + } + + protected boolean wakesUpForScheduledRunnable() { + return true; + } + /** * Adds a task to be run once at the end of next (or current) {@code eventloop} iteration. *
diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java deleted file mode 100644 index 5a9cb19a1ff..00000000000 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2014 The Netty Project - * - * The Netty Project licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -package io.netty.channel.epoll; - -import io.netty.channel.unix.FileDescriptor; -import org.junit.Test; - -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class EpollTest { - - @Test - public void testIsAvailable() { - assertTrue(Epoll.isAvailable()); - } - - // Testcase for https://github.com/netty/netty/issues/8444 - @Test(timeout = 5000) - public void testEpollWaitWithTimeOutMinusOne() throws Exception { - final EpollEventArray eventArray = new EpollEventArray(8); - try { - final FileDescriptor epoll = Native.newEpollCreate(); - final FileDescriptor timerFd = Native.newTimerFd(); - final FileDescriptor eventfd = Native.newEventFd(); - Native.epollCtlAdd(epoll.intValue(), timerFd.intValue(), Native.EPOLLIN); - Native.epollCtlAdd(epoll.intValue(), eventfd.intValue(), Native.EPOLLIN); - - final AtomicReference<Throwable> ref = new AtomicReference<Throwable>(); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - assertEquals(1, Native.epollWait(epoll, eventArray, timerFd, -1, -1)); - // This should have been woken up because of eventfd_write. - assertEquals(eventfd.intValue(), eventArray.fd(0)); - } catch (Throwable cause) { - ref.set(cause); - } - } - }); - t.start(); - t.join(1000); - assertTrue(t.isAlive()); - Native.eventFdWrite(eventfd.intValue(), 1); - - t.join(); - assertNull(ref.get()); - epoll.close(); - timerFd.close(); - eventfd.close(); - } finally { - eventArray.free(); - } - } -}
test
val
"2019-07-10T12:19:15"
"2018-03-31T18:08:22Z"
Scottmitch
val
netty/netty/7837_7839
netty/netty
netty/netty/7837
netty/netty/7839
[ "timestamp(timedelta=0.0, similarity=0.8714330086052116)" ]
473f6a6edb8353728ea8e711ac8241ddc21adf08
ee9057ad99b9cc95140ee3e56265f32b6a28d709
[ "@amizurov its a bug :(\r\n \r\nFixed https://github.com/netty/netty/pull/7839", "@normanmaurer Thanks a lot, It's really quickly as well as Netty :)" ]
[]
"2018-04-03T16:42:40Z"
[]
CorsHandler do writeAndFlush in override ChannelHandlerContext#write method
Do not really understand, why in `CorsHandler` invoked writeAndFlash ? It's strange side effect. ### Actual behavior https://github.com/netty/netty/blob/473f6a6edb8353728ea8e711ac8241ddc21adf08/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java#L198-L209 ### Steps to reproduce Add `CorsHandler` to pipeline then write response in your own handler, response flushed automatically. ### Netty version 4.1.22
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java index f4b5552b724..9e7756521e9 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cors/CorsHandler.java @@ -205,7 +205,7 @@ public void write(final ChannelHandlerContext ctx, final Object msg, final Chann setExposeHeaders(response); } } - ctx.writeAndFlush(msg, promise); + ctx.write(msg, promise); } private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
null
train
val
"2018-04-02T21:37:03"
"2018-04-03T13:07:47Z"
amizurov
val
netty/netty/7847_7848
netty/netty
netty/netty/7847
netty/netty/7848
[ "timestamp(timedelta=0.0, similarity=0.91396344380582)" ]
f8ff834f037e51b7119630bdb7713a29c18b8e31
f9604eeff5019219ea2895556309735bb27077fe
[]
[]
"2018-04-05T22:29:51Z"
[]
Http2ConnectionHandler doesn't set the correct header state for streams generated from upgrades
### Expected behavior When stream 1 is created from a h2c upgrade, the resultant stream should signal that it has sent the headers for the client, and that it has received the headers for the server. ### Actual behavior The stream state doesn't acknowledge that the request headers have been sent/received. ### Minimal yet complete reproducer code (or URL to code) Add the following test cases to the Http2ConnectionHandlerTest suite: ```java @Test public void clientUpgradeSetsStreamHeadersSent() throws Exception { when(local.createStream(STREAM_ID, true)).thenReturn(stream); handler = newHandler(); handler.onHttpClientUpgrade(); Http2Stream upgradeStream = handler.connection().stream(HTTP_UPGRADE_STREAM_ID); assertSame(stream, upgradeStream); verify(stream).headersSent(false); } @Test public void serverUpgradeSetsStreamHeadersReceived() throws Exception { when(connection.isServer()).thenReturn(true); when(remote.createStream(STREAM_ID, true)).thenReturn(stream); handler = newHandler(); handler.onHttpServerUpgrade(new Http2Settings()); Http2Stream upgradeStream = handler.connection().stream(HTTP_UPGRADE_STREAM_ID); assertSame(stream, upgradeStream); verify(stream).headersReceived(false); } ``` ### Netty version 4.1 branch. ### JVM version (e.g. `java -version`) openjdk version "1.8.0_162" ### OS version (e.g. `uname -a`) OSX Darwin Kernel Version 17.5.0
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java index 12815c225c8..42513174572 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Connection.java @@ -478,11 +478,19 @@ public Http2Stream open(boolean halfClosed) throws Http2Exception { if (!createdBy().canOpenStream()) { throw connectionError(PROTOCOL_ERROR, "Maximum active streams violated for this endpoint."); } + activate(); return this; } void activate() { + // If the stream is opened in a half-closed state, the headers must have either + // been sent if this is a local stream, or received if it is a remote stream. + if (state == HALF_CLOSED_LOCAL) { + headersSent(/*isInformational*/ false); + } else if (state == HALF_CLOSED_REMOTE) { + headersReceived(/*isInformational*/ false); + } activeStreams.activate(this); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java index 3b654425cf3..6db9d78a806 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Stream.java @@ -76,9 +76,9 @@ public boolean remoteSideOpen() { * <ul> * <li>{@link State#OPEN} if {@link #state()} is {@link State#IDLE} and {@code halfClosed} is {@code false}.</li> * <li>{@link State#HALF_CLOSED_LOCAL} if {@link #state()} is {@link State#IDLE} and {@code halfClosed} - * is {@code true} and the stream is local.</li> + * is {@code true} and the stream is local. In this state, {@link #isHeadersSent()} is {@code true}</li> * <li>{@link State#HALF_CLOSED_REMOTE} if {@link #state()} is {@link State#IDLE} and {@code halfClosed} - * is {@code true} and the stream is remote.</li> + * is {@code true} and the stream is remote. In this state, {@link #isHeadersReceived()} is {@code true}</li> * <li>{@link State#RESERVED_LOCAL} if {@link #state()} is {@link State#HALF_CLOSED_REMOTE}.</li> * <li>{@link State#RESERVED_REMOTE} if {@link #state()} is {@link State#HALF_CLOSED_LOCAL}.</li> * </ul>
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java index 966f668b405..ef385beed64 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2ConnectionTest.java @@ -294,12 +294,14 @@ public void clientCreateStreamShouldSucceed() throws Http2Exception { assertEquals(State.HALF_CLOSED_REMOTE, stream.state()); assertEquals(2, client.numActiveStreams()); assertEquals(4, client.remote().lastStreamCreated()); + assertTrue(stream.isHeadersReceived()); stream = client.local().createStream(3, true); assertEquals(3, stream.id()); assertEquals(State.HALF_CLOSED_LOCAL, stream.state()); assertEquals(3, client.numActiveStreams()); assertEquals(3, client.local().lastStreamCreated()); + assertTrue(stream.isHeadersSent()); stream = client.local().createStream(5, false); assertEquals(5, stream.id());
train
val
"2018-04-10T10:41:50"
"2018-04-05T22:21:34Z"
bryce-anderson
val
netty/netty/7825_7853
netty/netty
netty/netty/7825
netty/netty/7853
[ "timestamp(timedelta=34682.0, similarity=0.8800222931639644)", "keyword_pr_to_issue" ]
587afddb279bea3fd0f64d3421de8e69a35cecb9
a4146b706c0a0577f9ce65d711ad64a6847e3e24
[ "Looks like I can call `defaultHttp2HeadersEncoder.maxHeaderListSize(MAX_HEADER_LIST_SIZE)` to workaround this. If done immediately on creation, it looks like it won't collide with any received SETTINGS requesting a lower value.", "I've created a demo of this bug here: https://github.com/JLofgren/demo-grpc-java-bug-4284\r\n\r\nLocally I have built netty initializing the max header size in HpackEncoder to MAX_HEADER_LIST_SIZE and shown that this solves the issue. I am working on a PR, but am having some issues dotting all the i's of your PR process.\r\n" ]
[ "if you look at the comments for `DEFAULT_HEADER_LIST_SIZE` it describes that although the value is arbitrary it is not un-intentional, and technically not in violation of the spec. Having unlimited header size may leave the server exposed to memory exhaustion before it has the chance to communicate a lower limit. I think I would prefer to have the default value be configurable rather than just making it infinite. What about extracting the value from `AbstractHttp2ConnectionHandlerBuilder#initialSettings`?", "@Scottmitch Are you saying there is a possible scenario in the HTTP/2 protocol in which the receiver may be reading headers from the sender *before* the receiver has sent a settings frame to the sender?", "I guess I should say: ... *before* the receiver's settings frame has been processed by the sender?", "@Scottmitch ping", "doh ... I thought this was in the decoder. I took a look at the decoder and looks like we are already using my suggestion of inferring the value from the initial settings. Sorry for the noise ... lgtm." ]
"2018-04-06T18:59:15Z"
[ "defect" ]
HpackEncoder limits header list size to 8K by default
### Expected behavior Sending a header list of arbitrary size would succeed, except when the receiver prohibits header list larger than a certain size. RFC7540 defines SETTINGS_MAX_HEADER_LIST_SIZE's initial value to be unlimited. ### Actual behavior If the receiver does not specify a maximum header list size in SETTINGS, Netty disallows header list sizes greater than 8K. The problem seems to be [in HpackEncoder](https://github.com/netty/netty/blob/netty-4.1.22.Final/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java#L89). While defaulting to 8K makes sense for HpackDecoder in order for it to protect itself against the remote, there's no need for such behavior in HpackEncoder. In fact, since SETTINGS_MAX_HEADER_LIST_SIZE is advisory and the content is locally generated, it could ignore the setting completely and only risk wasting bandwidth. This was reported against gRPC at grpc/grpc-java#4284. CC @JLofgren ### Netty version 4.1.17.Final I'd be happy to send a PR changing the initialization to use `MAX_HEADER_LIST_SIZE`. @Scottmitch, @normanmaurer, concerns?
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java index b9a7703042f..7719072a499 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java @@ -41,7 +41,6 @@ import java.util.Map; import static io.netty.handler.codec.http2.HpackUtil.equalsConstantTime; -import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_HEADER_LIST_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_HEADER_TABLE_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_LIST_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.MAX_HEADER_TABLE_SIZE; @@ -86,7 +85,7 @@ public HpackEncoder(boolean ignoreMaxHeaderListSize) { public HpackEncoder(boolean ignoreMaxHeaderListSize, int arraySizeHint) { this.ignoreMaxHeaderListSize = ignoreMaxHeaderListSize; maxHeaderTableSize = DEFAULT_HEADER_TABLE_SIZE; - maxHeaderListSize = DEFAULT_HEADER_LIST_SIZE; + maxHeaderListSize = MAX_HEADER_LIST_SIZE; // Enforce a bound of [2, 128] because hashMask is a byte. The max possible value of hashMask is one less // than the length of this array, and we want the mask to be > 0. headerFields = new HeaderEntry[findNextPositivePowerOfTwo(max(2, min(arraySizeHint, 128)))];
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java index 2996b5db6b3..b1dce05c38b 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java @@ -56,4 +56,46 @@ public void testSetMaxHeaderTableSizeOverflow() throws Http2Exception { buf.release(); } } + + /** + * The encoder should not impose an arbitrary limit on the header size if + * the server has not specified any limit. + * @throws Http2Exception + */ + @Test + public void testWillEncode16MBHeaderByDefault() throws Http2Exception { + ByteBuf buf = Unpooled.buffer(); + String bigHeaderName = "x-big-header"; + int bigHeaderSize = 1024 * 1024 * 16; + String bigHeaderVal = new String(new char[bigHeaderSize]).replace('\0', 'X'); + Http2Headers headersIn = new DefaultHttp2Headers().add( + "x-big-header", bigHeaderVal); + Http2Headers headersOut = new DefaultHttp2Headers(); + + try { + hpackEncoder.encodeHeaders(0, buf, headersIn, Http2HeadersEncoder.NEVER_SENSITIVE); + hpackDecoder.setMaxHeaderListSize(bigHeaderSize + 1024, bigHeaderSize + 1024); + hpackDecoder.decode(0, buf, headersOut, false); + } finally { + buf.release(); + } + assertEquals(headersOut.get(bigHeaderName).toString(), bigHeaderVal); + } + + @Test(expected = Http2Exception.class) + public void testSetMaxHeaderListSizeEnforcedAfterSet() throws Http2Exception { + ByteBuf buf = Unpooled.buffer(); + Http2Headers headers = new DefaultHttp2Headers().add( + "x-big-header", + new String(new char[1024 * 16]).replace('\0', 'X') + ); + + hpackEncoder.setMaxHeaderListSize(1000); + + try { + hpackEncoder.encodeHeaders(0, buf, headers, Http2HeadersEncoder.NEVER_SENSITIVE); + } finally { + buf.release(); + } + } }
train
val
"2018-04-05T19:44:08"
"2018-03-30T23:52:20Z"
ejona86
val
netty/netty/7863_7864
netty/netty
netty/netty/7863
netty/netty/7864
[ "timestamp(timedelta=4113.0, similarity=0.9010866880266841)" ]
401b196623b9a2cadaf6ef8a67f2de2d360e8fe3
5891257ca0f09e41b894496bd0e2fc6843d93ec9
[ "@Stefan-Weber yes thanks... working on a patch" ]
[ "I think it will be more correct:\r\n```java\r\nfinal int len = offset + length - subCount;\r\n```\r\nthat is, do not add the `start` to the `len`.", "Agreed. There is also a bounds checking issue with the lastIndexOf below. See PR https://github.com/netty/netty/pull/7866", "sounds good ... let me close this one" ]
"2018-04-12T13:44:37Z"
[ "defect" ]
ArrayIndexOutOfBoundsException in AsciiString().indexOf()
### Actual behavior Calling the method indexOf() in a special case throws ArrayIndexOutOfBoundsException. java.lang.ArrayIndexOutOfBoundsException: 6 at io.netty.util.AsciiString.indexOf(AsciiString.java:693) at ByteBufsTests.indexOfSuccess(ByteBufsTests.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) ... ### Steps to reproduce Run the following 2 lines of JUnit code, I hope this is enough for reproduction. ### Minimal yet complete reproducer code (or URL to code) Assert.assertEquals("Test success in 4.1.(22|23).Final", 3, new AsciiString("012345").indexOf("345", 3)); Assert.assertEquals("Test fails with 'ArrayIndexOutOfBoundsException: 6' in 4.1.23.Final", -1, new AsciiString("012345").indexOf("abc", 3)); ### Netty version 4.1.23.Final ### JVM version (e.g. `java -version`) java version "1.8.0_66" Java(TM) SE Runtime Environment (build 1.8.0_66-b17) Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode) ### OS version (e.g. `uname -a`) Win7
[ "common/src/main/java/io/netty/util/AsciiString.java" ]
[ "common/src/main/java/io/netty/util/AsciiString.java" ]
[ "common/src/test/java/io/netty/util/AsciiStringCharacterTest.java" ]
diff --git a/common/src/main/java/io/netty/util/AsciiString.java b/common/src/main/java/io/netty/util/AsciiString.java index 17ef64f3287..621db211e52 100644 --- a/common/src/main/java/io/netty/util/AsciiString.java +++ b/common/src/main/java/io/netty/util/AsciiString.java @@ -689,7 +689,7 @@ public int indexOf(CharSequence subString, int start) { } final byte firstCharAsByte = c2b0(firstChar); final int len = offset + start + length - subCount; - for (int i = start + offset; i <= len; ++i) { + for (int i = start + offset; i <= len && i < length; ++i) { if (value[i] == firstCharAsByte) { int o1 = i, o2 = 0; while (++o2 < subCount && b2c(value[++o1]) == subString.charAt(o2)) { @@ -773,7 +773,7 @@ public int lastIndexOf(CharSequence subString, int start) { } final byte firstCharAsByte = c2b0(firstChar); final int end = offset + start; - for (int i = offset + start + length - subCount; i >= end; --i) { + for (int i = length - subCount; i >= end; --i) { if (value[i] == firstCharAsByte) { int o1 = i, o2 = 0; while (++o2 < subCount && b2c(value[++o1]) == subString.charAt(o2)) {
diff --git a/common/src/test/java/io/netty/util/AsciiStringCharacterTest.java b/common/src/test/java/io/netty/util/AsciiStringCharacterTest.java index 60686f18a8c..e80f4424dfb 100644 --- a/common/src/test/java/io/netty/util/AsciiStringCharacterTest.java +++ b/common/src/test/java/io/netty/util/AsciiStringCharacterTest.java @@ -385,4 +385,26 @@ public void testSubStringHashCode() { //two "123"s assertEquals(AsciiString.hashCode("123"), AsciiString.hashCode("a123".substring(1))); } + + @Test + public void testIndexOf() { + Assert.assertEquals(3, new AsciiString("012345").indexOf("345", 3)); + Assert.assertEquals(3, new AsciiString("012345").indexOf("345", 0)); + Assert.assertEquals(-1, new AsciiString("012345").indexOf("345", 4)); + Assert.assertEquals(-1, new AsciiString("012345").indexOf("abc", 3)); + Assert.assertEquals(-1, new AsciiString("012345").indexOf("abc", 0)); + Assert.assertEquals(-1, new AsciiString("012345").indexOf("abcdefghi", 0)); + Assert.assertEquals(-1, new AsciiString("012345").indexOf("abcdefghi", 4)); + } + + @Test + public void testLastIndexOf() { + Assert.assertEquals(3, new AsciiString("012345").lastIndexOf("345", 3)); + Assert.assertEquals(3, new AsciiString("012345").lastIndexOf("345", 0)); + Assert.assertEquals(-1, new AsciiString("012345").lastIndexOf("345", 4)); + Assert.assertEquals(-1, new AsciiString("012345").lastIndexOf("abc", 3)); + Assert.assertEquals(-1, new AsciiString("012345").lastIndexOf("abc", 0)); + Assert.assertEquals(-1, new AsciiString("012345").lastIndexOf("abcdefghi", 0)); + Assert.assertEquals(-1, new AsciiString("012345").lastIndexOf("abcdefghi", 4)); + } }
train
val
"2018-04-11T14:36:56"
"2018-04-12T11:03:40Z"
Stefan-Weber
val
netty/netty/7871_7872
netty/netty
netty/netty/7871
netty/netty/7872
[ "timestamp(timedelta=0.0, similarity=0.9472928157236656)" ]
81a7d1413bd36fc42be5ef3e67a55b0c56a2672f
0b690a991fb86903188e769763225ce9f3099b4c
[ "@kubuzetto PRs welcome", "Fixed via https://github.com/netty/netty/pull/7872" ]
[ "revert", "revert?", "Yes please revert this change ... ", "Do you mean the entire PR? Why?", "No just the one line change above the comment" ]
"2018-04-16T15:14:27Z"
[]
Add support for IP_TRANSPARENT socket option for UDP connections
Push request at #6835 does not include 'transparent proxy' mode for UDP. setOption() function in EpollDatagramChannelConfig should include IP_TRANSPARENT option.
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java" ]
[ "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java" ]
[]
diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java index ddb206551df..0f8e86ec1d9 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java @@ -23,6 +23,7 @@ import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.WriteBufferWaterMark; import io.netty.channel.socket.DatagramChannelConfig; + import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; @@ -48,7 +49,7 @@ public Map<ChannelOption<?>, Object> getOptions() { ChannelOption.SO_REUSEADDR, ChannelOption.IP_MULTICAST_LOOP_DISABLED, ChannelOption.IP_MULTICAST_ADDR, ChannelOption.IP_MULTICAST_IF, ChannelOption.IP_MULTICAST_TTL, ChannelOption.IP_TOS, ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, - EpollChannelOption.SO_REUSEPORT); + EpollChannelOption.SO_REUSEPORT, EpollChannelOption.IP_TRANSPARENT); } @SuppressWarnings({ "unchecked", "deprecation" }) @@ -87,6 +88,9 @@ public <T> T getOption(ChannelOption<T> option) { if (option == EpollChannelOption.SO_REUSEPORT) { return (T) Boolean.valueOf(isReusePort()); } + if (option == EpollChannelOption.IP_TRANSPARENT) { + return (T) Boolean.valueOf(isIpTransparent()); + } return super.getOption(option); } @@ -117,6 +121,8 @@ public <T> boolean setOption(ChannelOption<T> option, T value) { setActiveOnOpen((Boolean) value); } else if (option == EpollChannelOption.SO_REUSEPORT) { setReusePort((Boolean) value); + } else if (option == EpollChannelOption.IP_TRANSPARENT) { + setIpTransparent((Boolean) value); } else { return super.setOption(option, value); } @@ -371,4 +377,30 @@ public EpollDatagramChannelConfig setReusePort(boolean reusePort) { throw new ChannelException(e); } } + + /** + * Returns {@code true} if <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_TRANSPARENT</a> is enabled, + * {@code false} otherwise. + */ + public boolean isIpTransparent() { + try { + return datagramChannel.socket.isIpTransparent(); + } catch (IOException e) { + throw new ChannelException(e); + } + } + + /** + * If {@code true} is used <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_TRANSPARENT</a> is enabled, + * {@code false} for disable it. Default is disabled. + */ + public EpollDatagramChannelConfig setIpTransparent(boolean ipTransparent) { + try { + datagramChannel.socket.setIpTransparent(ipTransparent); + return this; + } catch (IOException e) { + throw new ChannelException(e); + } + } + }
null
val
val
"2018-04-16T12:11:42"
"2018-04-16T06:05:07Z"
kubuzetto
val
netty/netty/7877_7878
netty/netty
netty/netty/7877
netty/netty/7878
[ "timestamp(timedelta=0.0, similarity=0.9048913290150462)" ]
0b690a991fb86903188e769763225ce9f3099b4c
3ec29455af9642f6b20d7a309d3b6fb19c49b819
[ "@syermakov OMG... looking. Thanks for reporting", "Fixed by https://github.com/netty/netty/pull/7878" ]
[]
"2018-04-19T06:27:59Z"
[ "defect" ]
Eternal loop in Recycler.WeakOrderQueue.Head#run() that blocks ObjectCleaner thread and causes OOM.
Hi, looks like in commit 6eb9674bf5ded128cb230a31987f14816b7f1886 there is a problem that causes an eternal loop in `Recycler.WeakOrderQueue.Head#run()`: ``` public void run() { Link head = link; while (head != null) { reclaimSpace(LINK_CAPACITY); head = link.next; } } ``` should be ``` public void run() { Link head = link; while (head != null) { reclaimSpace(LINK_CAPACITY); head = head.next; } } ``` Note `head = link.next` vs `head = head.next` ### Expected behavior Recycler.WeakOrderQueue.Head#run() should not block forever. ### Actual behavior Recycler.WeakOrderQueue.Head#run() falls into an eternal loop and blocks ObjectCleaner thread. ### Steps to reproduce Please see below... ### Minimal yet complete reproducer code (or URL to code) Sorry for not providing a reproducer, this issues came out in our project's test suite as an OOM after a long run and we were able to find its cause only by analyzing the JVM heap dump. ### Netty version 4.1.23.Final ### JVM version (e.g. `java -version`) java version "1.8.0_162" Java(TM) SE Runtime Environment (build 1.8.0_162-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode) ### OS version (e.g. `uname -a`) Darwin MacBook-Pro-sy.local 17.5.0 Darwin Kernel Version 17.5.0: Mon Mar 5 22:24:32 PST 2018; root:xnu-4570.51.1~1/RELEASE_X86_64 x86_64
[ "common/src/main/java/io/netty/util/Recycler.java" ]
[ "common/src/main/java/io/netty/util/Recycler.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/Recycler.java b/common/src/main/java/io/netty/util/Recycler.java index fde88782218..e84adc5a9a6 100644 --- a/common/src/main/java/io/netty/util/Recycler.java +++ b/common/src/main/java/io/netty/util/Recycler.java @@ -261,7 +261,7 @@ public void run() { Link head = link; while (head != null) { reclaimSpace(LINK_CAPACITY); - head = link.next; + head = head.next; } }
null
val
val
"2018-04-17T09:07:02"
"2018-04-19T00:11:30Z"
syermakov
val
netty/netty/4950_7879
netty/netty
netty/netty/4950
netty/netty/7879
[ "timestamp(timedelta=0.0, similarity=0.881571595310132)" ]
b75f44db9a0d5255815bff076fe54dec72176ca5
b818852cdb0ee56ce3cf939e2faa538d519baabd
[ "Will check...\n", "Looks like netty cannot get the udp destination address. See:\n\nhttp://developerweb.net/viewtopic.php?id=4342\nhttp://developerweb.net/viewtopic.php?id=4169\n", "Thanks Windie for your comments. I think I have a better understanding of the problem now. IP_PKTINFO socket option should be set, in order to get the ancillary message with required extra information (Destination IP and more) available.\nJava doesn't seem to provide any API to set this socket option, but I've searched this repo and epoll sockets seem to be created with C code (https://github.com/netty/netty/blob/4.0/transport-native-epoll/src/main/c/netty_unix_socket.c). So, maybe is still possible to have the UDP destination address available... \n", "@mpolonio yep I think I can make it work for native transport. Stay tuned.\n", "Hi @normanmaurer, did you have the time to take a closer look on the issue?\n", "@mpolonio not yet... sorry super busy and not high priority atm :(\n", "Do you have any plans to address this?", "Sorry but I had no cycles yet to do this and its not very high on my to do list. That said we love contributions.", "Thanks a lot", "Although this seems to be fixed this quite does not work for us. We are using a loading balance with KeepAlive which receives traffic via VIP address. Than it is routed to individual hosts via Direct Routing. Direct Routing works by replacing the target MAC in a package addressed to the loadbalancer to its virtual / loadbalancer IP with the MAC of the designated target server and re-sending it. This requires the servers to accept packages for the given IP, so they need to configure the corresponding IP on some local looopback / dummy device. \r\nFor this we have setup dummy interfaces with VIP address on the server machines. UDP packages are received on the netty server that has been bootstrapped with IP_RECVORIGDSTADDR. \r\nDespite this msg.recipient() does not return the VIP address but the address of the server it has been routed for. I am not an expert for linux/bsd socketing so I am not sure if this is even supposed to work but I know there is software written in C (FreeRadius) which reads the correct address (VIP) as destination address of the received packet. \r\nWe are doing this as we need to respond to the UDP packet from the same received address specified by Radius Protocol.\r\nAny idea why this is not working and how it can be fixed? " ]
[ "final" ]
"2018-04-19T13:54:46Z"
[]
DatagramPacket.recipient() doesn't return the actual destination IP, but the IP the app is bound to
I'm using epoll (on previous versions of my app I was using NIO and I think the behaviour is the same) on an application that is listening on all available interfaces (0.0.0.0). When I try to get the actual UDP packet destination IP, DatagramPacket.recipient() returns 0.0.0.0 and not the real packet destination IP. It seems to always return the IP the app is bound to. Please, let me know if you need some extra information. SO: Ubuntu 14.04.4 Netty version: 4.0.32.Final
[ "transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java", "transport-native-unix-common/src/main/c/netty_unix_socket.c", "transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java" ]
[ "transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java", "transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java", "transport-native-unix-common/src/main/c/netty_unix_socket.c", "transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java" ]
[ "testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java", "transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramUnicastTest.java" ]
diff --git a/transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c b/transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c index 562eaa0b537..d6e3ead94fe 100644 --- a/transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c +++ b/transport-native-epoll/src/main/c/netty_epoll_linuxsocket.c @@ -107,6 +107,10 @@ static void netty_epoll_linuxsocket_setIpTransparent(JNIEnv* env, jclass clazz, netty_unix_socket_setOption(env, fd, SOL_IP, IP_TRANSPARENT, &optval, sizeof(optval)); } +static void netty_epoll_linuxsocket_setIpRecvOrigDestAddr(JNIEnv* env, jclass clazz, jint fd, jint optval) { + netty_unix_socket_setOption(env, fd, IPPROTO_IP, IP_RECVORIGDSTADDR, &optval, sizeof(optval)); +} + static void netty_epoll_linuxsocket_setTcpMd5Sig(JNIEnv* env, jclass clazz, jint fd, jbyteArray address, jint scopeId, jbyteArray key) { struct sockaddr_storage addr; socklen_t addrSize; @@ -193,6 +197,14 @@ static jint netty_epoll_linuxsocket_isIpTransparent(JNIEnv* env, jclass clazz, j return optval; } +static jint netty_epoll_linuxsocket_isIpRecvOrigDestAddr(JNIEnv* env, jclass clazz, jint fd) { + int optval; + if (netty_unix_socket_getOption(env, fd, IPPROTO_IP, IP_RECVORIGDSTADDR, &optval, sizeof(optval)) == -1) { + return -1; + } + return optval; +} + static void netty_epoll_linuxsocket_getTcpInfo(JNIEnv* env, jclass clazz, jint fd, jlongArray array) { struct tcp_info tcp_info; if (netty_unix_socket_getOption(env, fd, IPPROTO_TCP, TCP_INFO, &tcp_info, sizeof(tcp_info)) == -1) { @@ -345,12 +357,14 @@ static const JNINativeMethod fixed_method_table[] = { { "setTcpUserTimeout", "(II)V", (void *) netty_epoll_linuxsocket_setTcpUserTimeout }, { "setIpFreeBind", "(II)V", (void *) netty_epoll_linuxsocket_setIpFreeBind }, { "setIpTransparent", "(II)V", (void *) netty_epoll_linuxsocket_setIpTransparent }, + { "setIpRecvOrigDestAddr", "(II)V", (void *) netty_epoll_linuxsocket_setIpRecvOrigDestAddr }, { "getTcpKeepIdle", "(I)I", (void *) netty_epoll_linuxsocket_getTcpKeepIdle }, { "getTcpKeepIntvl", "(I)I", (void *) netty_epoll_linuxsocket_getTcpKeepIntvl }, { "getTcpKeepCnt", "(I)I", (void *) netty_epoll_linuxsocket_getTcpKeepCnt }, { "getTcpUserTimeout", "(I)I", (void *) netty_epoll_linuxsocket_getTcpUserTimeout }, { "isIpFreeBind", "(I)I", (void *) netty_epoll_linuxsocket_isIpFreeBind }, { "isIpTransparent", "(I)I", (void *) netty_epoll_linuxsocket_isIpTransparent }, + { "isIpRecvOrigDestAddr", "(I)I", (void *) netty_epoll_linuxsocket_isIpRecvOrigDestAddr }, { "getTcpInfo", "(I[J)V", (void *) netty_epoll_linuxsocket_getTcpInfo }, { "setTcpMd5Sig", "(I[BI[B)V", (void *) netty_epoll_linuxsocket_setTcpMd5Sig } // "sendFile" has a dynamic signature diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java index 3ade823275b..d03e3e72367 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollChannelOption.java @@ -31,6 +31,7 @@ public final class EpollChannelOption<T> extends UnixChannelOption<T> { valueOf(EpollChannelOption.class, "TCP_USER_TIMEOUT"); public static final ChannelOption<Boolean> IP_FREEBIND = valueOf("IP_FREEBIND"); public static final ChannelOption<Boolean> IP_TRANSPARENT = valueOf("IP_TRANSPARENT"); + public static final ChannelOption<Boolean> IP_RECVORIGDSTADDR = valueOf("IP_RECVORIGDSTADDR"); public static final ChannelOption<Integer> TCP_FASTOPEN = valueOf(EpollChannelOption.class, "TCP_FASTOPEN"); public static final ChannelOption<Boolean> TCP_FASTOPEN_CONNECT = valueOf(EpollChannelOption.class, "TCP_FASTOPEN_CONNECT"); diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java index 8cbc31adde7..a19191d5967 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannel.java @@ -470,13 +470,18 @@ void epollInReady() { break; } + InetSocketAddress localAddress = remoteAddress.localAddress(); + if (localAddress == null) { + localAddress = (InetSocketAddress) localAddress(); + } + allocHandle.incMessagesRead(1); allocHandle.lastBytesRead(remoteAddress.receivedAmount()); data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()); readPending = false; pipeline.fireChannelRead( - new DatagramPacket(data, (InetSocketAddress) localAddress(), remoteAddress)); + new DatagramPacket(data, localAddress, remoteAddress)); data = null; } while (allocHandle.continueReading()); diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java index 0f8e86ec1d9..fbc44c1bcc1 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/EpollDatagramChannelConfig.java @@ -49,7 +49,8 @@ public Map<ChannelOption<?>, Object> getOptions() { ChannelOption.SO_REUSEADDR, ChannelOption.IP_MULTICAST_LOOP_DISABLED, ChannelOption.IP_MULTICAST_ADDR, ChannelOption.IP_MULTICAST_IF, ChannelOption.IP_MULTICAST_TTL, ChannelOption.IP_TOS, ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, - EpollChannelOption.SO_REUSEPORT, EpollChannelOption.IP_TRANSPARENT); + EpollChannelOption.SO_REUSEPORT, EpollChannelOption.IP_TRANSPARENT, + EpollChannelOption.IP_RECVORIGDSTADDR); } @SuppressWarnings({ "unchecked", "deprecation" }) @@ -91,6 +92,9 @@ public <T> T getOption(ChannelOption<T> option) { if (option == EpollChannelOption.IP_TRANSPARENT) { return (T) Boolean.valueOf(isIpTransparent()); } + if (option == EpollChannelOption.IP_RECVORIGDSTADDR) { + return (T) Boolean.valueOf(isIpRecvOrigDestAddr()); + } return super.getOption(option); } @@ -123,6 +127,8 @@ public <T> boolean setOption(ChannelOption<T> option, T value) { setReusePort((Boolean) value); } else if (option == EpollChannelOption.IP_TRANSPARENT) { setIpTransparent((Boolean) value); + } else if (option == EpollChannelOption.IP_RECVORIGDSTADDR) { + setIpRecvOrigDestAddr((Boolean) value); } else { return super.setOption(option, value); } @@ -403,4 +409,29 @@ public EpollDatagramChannelConfig setIpTransparent(boolean ipTransparent) { } } + /** + * Returns {@code true} if <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_RECVORIGDSTADDR</a> is + * enabled, {@code false} otherwise. + */ + public boolean isIpRecvOrigDestAddr() { + try { + return datagramChannel.socket.isIpRecvOrigDestAddr(); + } catch (IOException e) { + throw new ChannelException(e); + } + } + + /** + * If {@code true} is used <a href="http://man7.org/linux/man-pages/man7/ip.7.html">IP_RECVORIGDSTADDR</a> is + * enabled, {@code false} for disable it. Default is disabled. + */ + public EpollDatagramChannelConfig setIpRecvOrigDestAddr(boolean ipTransparent) { + try { + datagramChannel.socket.setIpRecvOrigDestAddr(ipTransparent); + return this; + } catch (IOException e) { + throw new ChannelException(e); + } + } + } diff --git a/transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java b/transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java index af7e47a8709..f0a5304a74c 100644 --- a/transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java +++ b/transport-native-epoll/src/main/java/io/netty/channel/epoll/LinuxSocket.java @@ -99,6 +99,10 @@ void setIpTransparent(boolean enabled) throws IOException { setIpTransparent(intValue(), enabled ? 1 : 0); } + void setIpRecvOrigDestAddr(boolean enabled) throws IOException { + setIpRecvOrigDestAddr(intValue(), enabled ? 1 : 0); + } + void getTcpInfo(EpollTcpInfo info) throws IOException { getTcpInfo(intValue(), info.info); } @@ -148,6 +152,10 @@ boolean isIpTransparent() throws IOException { return isIpTransparent(intValue()) != 0; } + boolean isIpRecvOrigDestAddr() throws IOException { + return isIpRecvOrigDestAddr(intValue()) != 0; + } + PeerCredentials getPeerCredentials() throws IOException { return getPeerCredentials(intValue()); } @@ -189,6 +197,7 @@ private static native long sendFile(int socketFd, DefaultFileRegion src, long ba private static native int getTcpUserTimeout(int fd) throws IOException; private static native int isIpFreeBind(int fd) throws IOException; private static native int isIpTransparent(int fd) throws IOException; + private static native int isIpRecvOrigDestAddr(int fd) throws IOException; private static native void getTcpInfo(int fd, long[] array) throws IOException; private static native PeerCredentials getPeerCredentials(int fd) throws IOException; private static native int isTcpFastOpenConnect(int fd) throws IOException; @@ -205,5 +214,6 @@ private static native long sendFile(int socketFd, DefaultFileRegion src, long ba private static native void setTcpUserTimeout(int fd, int milliseconds)throws IOException; private static native void setIpFreeBind(int fd, int freeBind) throws IOException; private static native void setIpTransparent(int fd, int transparent) throws IOException; + private static native void setIpRecvOrigDestAddr(int fd, int transparent) throws IOException; private static native void setTcpMd5Sig(int fd, byte[] address, int scopeId, byte[] key) throws IOException; } diff --git a/transport-native-unix-common/src/main/c/netty_unix_socket.c b/transport-native-unix-common/src/main/c/netty_unix_socket.c index 7ab1a1e3c91..a9e0e11dd17 100644 --- a/transport-native-unix-common/src/main/c/netty_unix_socket.c +++ b/transport-native-unix-common/src/main/c/netty_unix_socket.c @@ -68,7 +68,7 @@ static int nettyNonBlockingSocket(int domain, int type, int protocol) { #endif } -static jobject createDatagramSocketAddress(JNIEnv* env, const struct sockaddr_storage* addr, int len) { +static jobject createDatagramSocketAddress(JNIEnv* env, const struct sockaddr_storage* addr, int len, jobject local) { char ipstr[INET6_ADDRSTRLEN]; int port; jstring ipString; @@ -93,7 +93,7 @@ static jobject createDatagramSocketAddress(JNIEnv* env, const struct sockaddr_st ipString = (*env)->NewStringUTF(env, ipstr); } } - jobject socketAddr = (*env)->NewObject(env, datagramSocketAddressClass, datagramSocketAddrMethodId, ipString, port, len); + jobject socketAddr = (*env)->NewObject(env, datagramSocketAddressClass, datagramSocketAddrMethodId, ipString, port, len, local); return socketAddr; } @@ -289,12 +289,39 @@ static jint _sendTo(JNIEnv* env, jint fd, void* buffer, jint pos, jint limit, jb static jobject _recvFrom(JNIEnv* env, jint fd, void* buffer, jint pos, jint limit) { struct sockaddr_storage addr; + struct sockaddr_storage daddr; socklen_t addrlen = sizeof(addr); + char cntrlbuf[64]; + struct iovec iov; + struct msghdr msg; ssize_t res; int err; + struct cmsghdr* cmsg; + jobject local = NULL; + int readLocalAddr; + + if (netty_unix_socket_getOption(env, fd, IPPROTO_IP, IP_RECVORIGDSTADDR, + &readLocalAddr, sizeof(readLocalAddr)) < 0) { + readLocalAddr = 0; + } + + if (readLocalAddr) { + iov.iov_base = buffer + pos; + iov.iov_len = (size_t) (limit - pos); + msg.msg_name = (struct sockaddr*) &addr; + msg.msg_namelen = addrlen; + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = cntrlbuf; + msg.msg_controllen = sizeof(cntrlbuf); + } do { - res = recvfrom(fd, buffer + pos, (size_t) (limit - pos), 0, (struct sockaddr*) &addr, &addrlen); + if (readLocalAddr) { + res = recvmsg(fd, &msg, 0); + } else { + res = recvfrom(fd, buffer + pos, (size_t) (limit - pos), 0, (struct sockaddr*) &addr, &addrlen); + } // Keep on reading if we was interrupted } while (res == -1 && ((err = errno) == EINTR)); @@ -315,7 +342,16 @@ static jobject _recvFrom(JNIEnv* env, jint fd, void* buffer, jint pos, jint limi return NULL; } - return createDatagramSocketAddress(env, &addr, res); + if (readLocalAddr) { + for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_RECVORIGDSTADDR) { + memcpy (&daddr, CMSG_DATA(cmsg), sizeof (struct sockaddr_storage)); + local = createDatagramSocketAddress(env, &daddr, res, NULL); + break; + } + } + } + return createDatagramSocketAddress(env, &addr, res, local); } void netty_unix_socket_getOptionHandleError(JNIEnv* env, int err) { @@ -977,9 +1013,9 @@ jint netty_unix_socket_JNI_OnLoad(JNIEnv* env, const char* packagePrefix) { netty_unix_errors_throwOutOfMemoryError(env); return JNI_ERR; } - datagramSocketAddrMethodId = (*env)->GetMethodID(env, datagramSocketAddressClass, "<init>", "(Ljava/lang/String;II)V"); + datagramSocketAddrMethodId = (*env)->GetMethodID(env, datagramSocketAddressClass, "<init>", "(Ljava/lang/String;IILio/netty/channel/unix/DatagramSocketAddress;)V"); if (datagramSocketAddrMethodId == NULL) { - netty_unix_errors_throwRuntimeException(env, "failed to get method ID: DatagramSocketAddress.<init>(String, int, int)"); + netty_unix_errors_throwRuntimeException(env, "failed to get method ID: DatagramSocketAddress.<init>(String, int, int, DatagramSocketAddress)"); return JNI_ERR; } jclass localInetSocketAddressClass = (*env)->FindClass(env, "java/net/InetSocketAddress"); diff --git a/transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java b/transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java index 21d7215a49c..874d7054f51 100644 --- a/transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java +++ b/transport-native-unix-common/src/main/java/io/netty/channel/unix/DatagramSocketAddress.java @@ -28,10 +28,16 @@ public final class DatagramSocketAddress extends InetSocketAddress { // holds the amount of received bytes private final int receivedAmount; + private final DatagramSocketAddress localAddress; - DatagramSocketAddress(String addr, int port, int receivedAmount) { + DatagramSocketAddress(String addr, int port, int receivedAmount, DatagramSocketAddress local) { super(addr, port); this.receivedAmount = receivedAmount; + localAddress = local; + } + + public DatagramSocketAddress localAddress() { + return localAddress; } public int receivedAmount() {
diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java index 26743ba8c70..b49f6780ef5 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/DatagramUnicastTest.java @@ -277,6 +277,10 @@ public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws E for (byte b : bytes) { assertEquals(b, buf.readByte()); } + + // Test that the channel's localAddress is equal to the message's recipient + assertEquals(ctx.channel().localAddress(), msg.recipient()); + latch.countDown(); } }); diff --git a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramUnicastTest.java b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramUnicastTest.java index 610cfb5d851..a8ed58ed257 100644 --- a/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramUnicastTest.java +++ b/transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDatagramUnicastTest.java @@ -26,4 +26,11 @@ public class EpollDatagramUnicastTest extends DatagramUnicastTest { protected List<TestsuitePermutation.BootstrapComboFactory<Bootstrap, Bootstrap>> newFactories() { return EpollSocketTestPermutation.INSTANCE.datagram(); } + + public void testSimpleSendWithConnect(Bootstrap sb, Bootstrap cb) throws Throwable { + // Run this test with IP_RECVORIGDSTADDR option enabled + sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, true); + super.testSimpleSendWithConnect(sb, cb); + sb.option(EpollChannelOption.IP_RECVORIGDSTADDR, false); + } }
train
val
"2018-04-19T13:56:07"
"2016-03-07T13:57:03Z"
mpolonio
val
netty/netty/7880_7885
netty/netty
netty/netty/7880
netty/netty/7885
[ "timestamp(timedelta=0.0, similarity=0.8924957798753058)" ]
1b1f7677acec6a5ae06a552adc4c046b2ce2490d
f4d7e8de140048047299808bb7e707c15342b826
[ "@normanmaurer do you mean MAX_MESSAGES_PER_READ in netty-5.0.0.Alpha ?", "Ups yes https://github.com/netty/netty/blob/4.1/transport/src/main/java/io/netty/channel/ChannelOption.java#L83" ]
[]
"2018-04-23T13:16:38Z"
[ "defect" ]
LocalChannel / LocalServerChannel not respect ChannelOption. MAX_MESSAGES_PER_READ
LocalChannel / LocalServerChannel not respect ChannelOption.MAX_MESSAGES_PER_READ and just keeps processing messages until there are no more present.
[ "transport/src/main/java/io/netty/channel/local/LocalChannel.java", "transport/src/main/java/io/netty/channel/local/LocalServerChannel.java" ]
[ "transport/src/main/java/io/netty/channel/local/LocalChannel.java", "transport/src/main/java/io/netty/channel/local/LocalServerChannel.java" ]
[ "transport/src/test/java/io/netty/channel/local/LocalChannelTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/local/LocalChannel.java b/transport/src/main/java/io/netty/channel/local/LocalChannel.java index 0d4ca82075c..62bd4d6a1cb 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalChannel.java +++ b/transport/src/main/java/io/netty/channel/local/LocalChannel.java @@ -25,6 +25,7 @@ import io.netty.channel.DefaultChannelConfig; import io.netty.channel.EventLoop; import io.netty.channel.PreferHeapByteBufAllocator; +import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.SingleThreadEventLoop; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.Future; @@ -67,17 +68,13 @@ private enum State { OPEN, BOUND, CONNECTED, CLOSED } private final Runnable readTask = new Runnable() { @Override public void run() { - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); + // Ensure the inboundBuffer is not empty as readInbound() will always call fireChannelReadComplete() + if (!inboundBuffer.isEmpty()) { + readInbound(); } - pipeline.fireChannelReadComplete(); } }; + private final Runnable shutdownHook = new Runnable() { @Override public void run() { @@ -295,13 +292,27 @@ protected void doDeregister() throws Exception { ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook); } + private void readInbound() { + RecvByteBufAllocator.Handle handle = unsafe().recvBufAllocHandle(); + handle.reset(config()); + ChannelPipeline pipeline = pipeline(); + do { + Object received = inboundBuffer.poll(); + if (received == null) { + break; + } + pipeline.fireChannelRead(received); + } while (handle.continueReading()); + + pipeline.fireChannelReadComplete(); + } + @Override protected void doBeginRead() throws Exception { if (readInProgress) { return; } - ChannelPipeline pipeline = pipeline(); Queue<Object> inboundBuffer = this.inboundBuffer; if (inboundBuffer.isEmpty()) { readInProgress = true; @@ -313,14 +324,7 @@ protected void doBeginRead() throws Exception { if (stackDepth < MAX_READER_STACK_DEPTH) { threadLocals.setLocalChannelReaderStackDepth(stackDepth + 1); try { - for (;;) { - Object received = inboundBuffer.poll(); - if (received == null) { - break; - } - pipeline.fireChannelRead(received); - } - pipeline.fireChannelReadComplete(); + readInbound(); } finally { threadLocals.setLocalChannelReaderStackDepth(stackDepth); } @@ -435,19 +439,11 @@ private void finishPeerRead0(LocalChannel peer) { FINISH_READ_FUTURE_UPDATER.compareAndSet(peer, peerFinishReadFuture, null); } } - ChannelPipeline peerPipeline = peer.pipeline(); // We should only set readInProgress to false if there is any data that was read as otherwise we may miss to // forward data later on. if (peer.readInProgress && !peer.inboundBuffer.isEmpty()) { peer.readInProgress = false; - for (;;) { - Object received = peer.inboundBuffer.poll(); - if (received == null) { - break; - } - peerPipeline.fireChannelRead(received); - } - peerPipeline.fireChannelReadComplete(); + peer.readInbound(); } } diff --git a/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java b/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java index 422435cd182..6b3437547a2 100644 --- a/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java +++ b/transport/src/main/java/io/netty/channel/local/LocalServerChannel.java @@ -21,6 +21,7 @@ import io.netty.channel.DefaultChannelConfig; import io.netty.channel.EventLoop; import io.netty.channel.PreferHeapByteBufAllocator; +import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.ServerChannel; import io.netty.channel.SingleThreadEventLoop; import io.netty.util.concurrent.SingleThreadEventExecutor; @@ -126,15 +127,7 @@ protected void doBeginRead() throws Exception { return; } - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); - } - pipeline.fireChannelReadComplete(); + readInbound(); } LocalChannel serve(final LocalChannel peer) { @@ -143,15 +136,30 @@ LocalChannel serve(final LocalChannel peer) { serve0(child); } else { eventLoop().execute(new Runnable() { - @Override - public void run() { - serve0(child); - } + @Override + public void run() { + serve0(child); + } }); } return child; } + private void readInbound() { + RecvByteBufAllocator.Handle handle = unsafe().recvBufAllocHandle(); + handle.reset(config()); + ChannelPipeline pipeline = pipeline(); + do { + Object m = inboundBuffer.poll(); + if (m == null) { + break; + } + pipeline.fireChannelRead(m); + } while (handle.continueReading()); + + pipeline.fireChannelReadComplete(); + } + /** * A factory method for {@link LocalChannel}s. Users may override it * to create custom instances of {@link LocalChannel}s. @@ -164,15 +172,8 @@ private void serve0(final LocalChannel child) { inboundBuffer.add(child); if (acceptInProgress) { acceptInProgress = false; - ChannelPipeline pipeline = pipeline(); - for (;;) { - Object m = inboundBuffer.poll(); - if (m == null) { - break; - } - pipeline.fireChannelRead(m); - } - pipeline.fireChannelReadComplete(); + + readInbound(); } } }
diff --git a/transport/src/test/java/io/netty/channel/local/LocalChannelTest.java b/transport/src/test/java/io/netty/channel/local/LocalChannelTest.java index 2ec4c29a6a4..628f621f4e1 100644 --- a/transport/src/test/java/io/netty/channel/local/LocalChannelTest.java +++ b/transport/src/test/java/io/netty/channel/local/LocalChannelTest.java @@ -46,11 +46,13 @@ import java.nio.channels.ClosedChannelException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; @@ -1020,4 +1022,176 @@ public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exce closeChannel(sc); } } + + @Test(timeout = 5000) + public void testMaxMessagesPerReadRespectedWithAutoReadSharedGroup() throws Exception { + testMaxMessagesPerReadRespected(sharedGroup, sharedGroup, true); + } + + @Test(timeout = 5000) + public void testMaxMessagesPerReadRespectedWithoutAutoReadSharedGroup() throws Exception { + testMaxMessagesPerReadRespected(sharedGroup, sharedGroup, false); + } + + @Test(timeout = 5000) + public void testMaxMessagesPerReadRespectedWithAutoReadDifferentGroup() throws Exception { + testMaxMessagesPerReadRespected(group1, group2, true); + } + + @Test(timeout = 5000) + public void testMaxMessagesPerReadRespectedWithoutAutoReadDifferentGroup() throws Exception { + testMaxMessagesPerReadRespected(group1, group2, false); + } + + private static void testMaxMessagesPerReadRespected( + EventLoopGroup serverGroup, EventLoopGroup clientGroup, final boolean autoRead) throws Exception { + final CountDownLatch countDownLatch = new CountDownLatch(5); + Bootstrap cb = new Bootstrap(); + ServerBootstrap sb = new ServerBootstrap(); + + cb.group(serverGroup) + .channel(LocalChannel.class) + .option(ChannelOption.AUTO_READ, autoRead) + .option(ChannelOption.MAX_MESSAGES_PER_READ, 1) + .handler(new ChannelReadHandler(countDownLatch, autoRead)); + sb.group(clientGroup) + .channel(LocalServerChannel.class) + .childHandler(new ChannelInboundHandlerAdapter() { + @Override + public void channelActive(final ChannelHandlerContext ctx) { + for (int i = 0; i < 10; i++) { + ctx.write(i); + } + ctx.flush(); + } + }); + + Channel sc = null; + Channel cc = null; + try { + // Start server + sc = sb.bind(TEST_ADDRESS).sync().channel(); + cc = cb.connect(TEST_ADDRESS).sync().channel(); + + countDownLatch.await(); + } finally { + closeChannel(cc); + closeChannel(sc); + } + } + + @Test(timeout = 5000) + public void testServerMaxMessagesPerReadRespectedWithAutoReadSharedGroup() throws Exception { + testServerMaxMessagesPerReadRespected(sharedGroup, sharedGroup, true); + } + + @Test(timeout = 5000) + public void testServerMaxMessagesPerReadRespectedWithoutAutoReadSharedGroup() throws Exception { + testServerMaxMessagesPerReadRespected(sharedGroup, sharedGroup, false); + } + + @Test(timeout = 5000) + public void testServerMaxMessagesPerReadRespectedWithAutoReadDifferentGroup() throws Exception { + testServerMaxMessagesPerReadRespected(group1, group2, true); + } + + @Test(timeout = 5000) + public void testServerMaxMessagesPerReadRespectedWithoutAutoReadDifferentGroup() throws Exception { + testServerMaxMessagesPerReadRespected(group1, group2, false); + } + + private void testServerMaxMessagesPerReadRespected( + EventLoopGroup serverGroup, EventLoopGroup clientGroup, final boolean autoRead) throws Exception { + final CountDownLatch countDownLatch = new CountDownLatch(5); + Bootstrap cb = new Bootstrap(); + ServerBootstrap sb = new ServerBootstrap(); + + cb.group(serverGroup) + .channel(LocalChannel.class) + .handler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + // NOOP + } + }); + + sb.group(clientGroup) + .channel(LocalServerChannel.class) + .option(ChannelOption.AUTO_READ, autoRead) + .option(ChannelOption.MAX_MESSAGES_PER_READ, 1) + .handler(new ChannelReadHandler(countDownLatch, autoRead)) + .childHandler(new ChannelInitializer<Channel>() { + @Override + protected void initChannel(Channel ch) { + // NOOP + } + }); + + Channel sc = null; + Channel cc = null; + try { + // Start server + sc = sb.bind(TEST_ADDRESS).sync().channel(); + for (int i = 0; i < 5; i++) { + try { + cc = cb.connect(TEST_ADDRESS).sync().channel(); + } finally { + closeChannel(cc); + } + } + + countDownLatch.await(); + } finally { + closeChannel(sc); + } + } + + private static final class ChannelReadHandler extends ChannelInboundHandlerAdapter { + + private final CountDownLatch latch; + private final boolean autoRead; + private int read; + + ChannelReadHandler(CountDownLatch latch, boolean autoRead) { + this.latch = latch; + this.autoRead = autoRead; + } + + @Override + public void channelActive(ChannelHandlerContext ctx) { + if (!autoRead) { + ctx.read(); + } + ctx.fireChannelActive(); + } + + @Override + public void channelRead(final ChannelHandlerContext ctx, Object msg) { + assertEquals(0, read); + read++; + ctx.fireChannelRead(msg); + } + + @Override + public void channelReadComplete(final ChannelHandlerContext ctx) { + assertEquals(1, read); + latch.countDown(); + if (latch.getCount() > 0) { + if (!autoRead) { + // The read will be scheduled 100ms in the future to ensure we not receive any + // channelRead calls in the meantime. + ctx.executor().schedule(new Runnable() { + @Override + public void run() { + read = 0; + ctx.read(); + } + }, 100, TimeUnit.MILLISECONDS); + } else { + read = 0; + } + } + ctx.fireChannelReadComplete(); + } + } }
train
val
"2018-04-23T08:31:30"
"2018-04-19T19:07:52Z"
normanmaurer
val
netty/netty/7888_7891
netty/netty
netty/netty/7888
netty/netty/7891
[ "timestamp(timedelta=0.0, similarity=0.8822347332564776)" ]
c0ae5e697c3c4fdf81f0cfc199d18aacd3b8ecba
c60263e8a3336aae182fdde2dd0202a667cba880
[ "Also verified the same behavior on Netty 4.1.24.Final.", "@nicmunroe PTAL https://github.com/netty/netty/pull/7891" ]
[]
"2018-04-25T13:34:50Z"
[]
HttpResponseEncoder does not treat status 205 as a content-is-always-empty response
### Expected behavior RFC 2616 (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6) states that responses with HTTP status code 205 should never return a payload: `The response MUST NOT include an entity`. Additionally, the RFC 7230 section on content-length (https://tools.ietf.org/html/rfc7230#section-3.3.2) does not call out 205 responses as being in the allowed-to-lie-about-content-length category (only HEAD and 204 responses are in that category). Also from that RFC 7230 section, 205 responses are not in the must-never-send-content-length category (only 1xx, 204, and CONNECT with a 2xx are in that category). So based on that I would expect that when Netty encodes a 205 response it should: * Strip out any payload (other than the no-data chunk when transfer-encoding is chunked) * Set content-length to 0 for non-chunked responses NOTE: The HTTP spec is obviously difficult to follow on these corner cases. Please double check my logic on this issue - I believe my analysis to be correct based on my reading of those RFCs, but I could have interpreted it wrong, or I might be missing something in these RFCs or another spec doc entirely that explains how to handle 205 more directly than what I've cobbled together here. ### Actual behavior Netty does not currently do any smart filtering for 205 responses like it does for other always-empty responses (204, 304, HEAD, etc). I can send a 205 response with a payload and that payload will be sent over the wire as if it was a 200. Netty *does* appear to sort of pay attention to this on the decoding side - i.e. HttpRequestDecoder drops the payload on the floor if it sees an incoming 205 with a payload. So this issue is mainly about the HttpResponseEncoder side (unless you find something I missed). ### Steps to reproduce Send a 205 response with a payload from a Netty server and monitor the bytes on the wire. You'll see the payload is sent, and content-length is not set to 0 for non-chunked responses. ### Minimal yet complete reproducer code (or URL to code) ``` java import org.junit.*; import java.io.IOException; import java.net.ServerSocket; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import io.netty.bootstrap.*; import io.netty.buffer.*; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.*; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.EventExecutorGroup; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaders.Values.CHUNKED; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.netty.util.CharsetUtil.UTF_8; import static org.junit.Assert.assertTrue; public class NettyResponseEncodingSanitizingForHttpStatus205Test { private static int serverPort; private static final List<EventLoopGroup> eventLoopGroups = new ArrayList<>(); private static final List<Channel> channels = new ArrayList<>(); private static final String RESPONSE_PAYLOAD = UUID.randomUUID().toString(); private static StringBuilder nettyServerRawResponse; private static CompletableFuture<FullHttpResponse> responseFuture; private static boolean responseShouldBeChunked = false; public static int findFreePort() throws IOException { try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } } @Test public void verify_netty_encodes_http_status_205_responses_as_always_empty_non_chunked() throws Exception { executeRequestFor205Response(false); String rawResponse = nettyServerRawResponse.toString(); String rawResponseBody = extractBodyFromResponse(rawResponse); assertTrue( "The response payload should have been stripped out by Netty when encoding the 205 response, " + "but the response payload was still sent. Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), !rawResponse.contains(RESPONSE_PAYLOAD) ); assertTrue( "The Netty response encoder should have set the content-length header to a value of 0 for a " + "non-chunked 205 response, but didn't. Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), rawResponse.toLowerCase().contains("content-length: 0\r\n") ); assertTrue( "The response payload should have been completely empty, but found a non-empty payload instead. " + "Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), rawResponseBody.isEmpty() ); } @Test public void verify_netty_encodes_http_status_205_responses_as_always_empty_chunked() throws Exception { executeRequestFor205Response(true); String rawResponse = nettyServerRawResponse.toString(); String rawResponseBody = extractBodyFromResponse(rawResponse); assertTrue( "The response payload should have been stripped out by Netty when encoding the 205 response, " + "but the response payload was still sent. Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), !rawResponse.contains(RESPONSE_PAYLOAD) ); assertTrue( "Expecting to find 'transfer-encoding: chunked' header for chunked response. " + "Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), rawResponse.toLowerCase().contains("transfer-encoding: chunked\r\n") ); assertTrue( "The response payload should have been completely empty other than the zero-data chunk " + "'0\\r\\n\\r\\n', but found a non-empty payload instead. " + "Raw bytes-on-the-wire response: " + escapedRawResponse(rawResponse), rawResponseBody.equals("0\r\n\r\n") ); } private String extractBodyFromResponse(String response) { String bodyStartCrLfs = "\r\n\r\n"; int indexOfBodyStartCrLfs = response.indexOf(bodyStartCrLfs); return response.substring(indexOfBodyStartCrLfs + bodyStartCrLfs.length()); } private void executeRequestFor205Response(boolean chunkedResponse) throws Exception { responseShouldBeChunked = chunkedResponse; Bootstrap clientBootstrap = createNettyHttpClientBootstrap(); Channel clientChannel = connectNettyHttpClientToLocalServer(clientBootstrap, serverPort); clientChannel.writeAndFlush(new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/does/not/matter")); // We don't want the actual response, we just need to know when it's done so we can inspect the // aggregated bytes-on-the-wire via nettyServerRawResponse. responseFuture.get(5, TimeUnit.SECONDS); } private String escapedRawResponse(String escapeMe) { return escapeMe.replace("\r", "\\r").replace("\n", "\\n"); } private static ChannelHandler serverRequestHandler() { return new SimpleChannelInboundHandler<HttpObject>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof LastHttpContent) { List<HttpObject> responseChunks = (responseShouldBeChunked) ? handleChunkedResponse() : handleFullResponse(); responseChunks.forEach(ctx::write); ctx.flush(); } } private List<HttpObject> handleFullResponse() { ByteBuf responsePayload = Unpooled.wrappedBuffer(RESPONSE_PAYLOAD.getBytes(CharsetUtil.UTF_8)); FullHttpResponse fullResponse = new DefaultFullHttpResponse( HTTP_1_1, HttpResponseStatus.valueOf(205), responsePayload ); fullResponse.headers().set(CONTENT_LENGTH, responsePayload.readableBytes()); return Collections.singletonList(fullResponse); } private List<HttpObject> handleChunkedResponse() { ByteBuf responsePayload = Unpooled.wrappedBuffer(RESPONSE_PAYLOAD.getBytes(CharsetUtil.UTF_8)); HttpResponse firstChunk = new DefaultHttpResponse( HTTP_1_1, HttpResponseStatus.valueOf(205) ); firstChunk.headers().set(TRANSFER_ENCODING, CHUNKED); HttpContent contentChunk = new DefaultHttpContent(responsePayload); return Arrays.asList(firstChunk, contentChunk, LastHttpContent.EMPTY_LAST_CONTENT); } }; } public static Bootstrap createNettyHttpClientBootstrap() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); p.addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) { // Complete the future so the tests know the response is done. responseFuture.complete(msg); } }); } }); return bootstrap; } public static Channel connectNettyHttpClientToLocalServer(Bootstrap bootstrap, int port) throws InterruptedException { return bootstrap.connect("localhost", port).sync().channel(); } public static class RecordNettyServerOutboundResponseWireBytes extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; nettyServerRawResponse.append(byteBuf.toString(UTF_8)); super.write(ctx, msg, promise); } } @Before public void beforeMethod() { nettyServerRawResponse = new StringBuilder(); responseFuture = new CompletableFuture<>(); } @BeforeClass public static void beforeClass() throws IOException, InterruptedException { serverPort = findFreePort(); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); Class<? extends ServerChannel> channelClass = NioServerSocketChannel.class; eventLoopGroups.add(bossGroup); eventLoopGroups.add(workerGroup); ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new RecordNettyServerOutboundResponseWireBytes()); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(serverRequestHandler()); } }; // Create the server bootstrap ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(channelClass) .childHandler(channelInitializer); // Bind the server to the desired port and start it up so it is ready to receive requests Channel ch = b.bind(serverPort) .sync() .channel(); channels.add(ch); } @AfterClass public static void afterClass() throws InterruptedException { try { List<ChannelFuture> channelCloseFutures = new ArrayList<>(); for (Channel ch : channels) { channelCloseFutures.add(ch.close()); } for (ChannelFuture chf : channelCloseFutures) { chf.sync(); } } finally { eventLoopGroups.forEach(EventExecutorGroup::shutdownGracefully); } } } ``` ### Netty version 4.0.56.Final ### JVM version (e.g. `java -version`) 1.8.0_151 ### OS version (e.g. `uname -a`) Mac OSX 10.12.6 (Darwin AP10FD59C71492 16.7.0 Darwin Kernel Version 16.7.0: Thu Jan 11 22:59:40 PST 2018; root:xnu-3789.73.8~1/RELEASE_X86_64 x86_64)
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java index 60086cfd8a2..5ad7a7938e7 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseEncoder.java @@ -53,6 +53,14 @@ protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmp // Stripping Transfer-Encoding: // See https://tools.ietf.org/html/rfc7230#section-3.3.1 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); + } else if (status.code() == HttpResponseStatus.RESET_CONTENT.code()) { + + // Stripping Transfer-Encoding: + msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); + + // Set Content-Length: 0 + // https://httpstatuses.com/205 + msg.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0); } } } @@ -74,6 +82,7 @@ protected boolean isContentAlwaysEmpty(HttpResponse msg) { return true; } return status.code() == HttpResponseStatus.NO_CONTENT.code() || - status.code() == HttpResponseStatus.NOT_MODIFIED.code(); + status.code() == HttpResponseStatus.NOT_MODIFIED.code() || + status.code() == HttpResponseStatus.RESET_CONTENT.code(); } }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java index 218f6bdf748..2cd07e1018b 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpResponseEncoderTest.java @@ -353,4 +353,48 @@ private void testEmptyContents(boolean chunked, boolean trailers) throws Excepti lastContent.release(); assertFalse(channel.finish()); } + + @Test + public void testStatusResetContentTransferContentLength() { + testStatusResetContentTransferContentLength0(HttpHeaderNames.CONTENT_LENGTH, Unpooled.buffer().writeLong(8)); + } + + @Test + public void testStatusResetContentTransferEncoding() { + testStatusResetContentTransferContentLength0(HttpHeaderNames.TRANSFER_ENCODING, Unpooled.buffer().writeLong(8)); + } + + private static void testStatusResetContentTransferContentLength0(CharSequence headerName, ByteBuf content) { + EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseEncoder()); + + HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.RESET_CONTENT); + if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(headerName)) { + response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); + } else { + response.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); + } + + assertTrue(channel.writeOutbound(response)); + assertTrue(channel.writeOutbound(new DefaultHttpContent(content))); + assertTrue(channel.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT)); + + StringBuilder responseText = new StringBuilder(); + responseText.append(HttpVersion.HTTP_1_1.toString()).append(' ') + .append(HttpResponseStatus.RESET_CONTENT.toString()).append("\r\n"); + responseText.append(HttpHeaderNames.CONTENT_LENGTH).append(": 0\r\n"); + responseText.append("\r\n"); + + StringBuilder written = new StringBuilder(); + for (;;) { + ByteBuf buffer = channel.readOutbound(); + if (buffer == null) { + break; + } + written.append(buffer.toString(CharsetUtil.US_ASCII)); + buffer.release(); + } + + assertEquals(responseText.toString(), written.toString()); + assertFalse(channel.finish()); + } }
train
val
"2018-04-26T08:04:01"
"2018-04-25T01:14:11Z"
nicmunroe
val
netty/netty/7887_7911
netty/netty
netty/netty/7887
netty/netty/7911
[ "timestamp(timedelta=0.0, similarity=0.9201288709387265)", "keyword_pr_to_issue" ]
85e2987719fb6e196feb13a21560cc1ea589e24a
88f0586a7e89a4e35e0011bdf607b3192bfe7b5f
[ "I think what you said @ejona86 makes sense... want to do a pr ?", "I worked on the change last night :) but didn't send it out because I was investigating further changes. Sent it out now." ]
[ "s/max/goAwayMax/", "\"positive or zero\"?", "Yeah, looks like it should be \"non-negative\". This was pre-existing code and just moved, but I can update it.", "@ejona86 move this to the public method (as it was before) ?", "@ejona86 should we just keep the method as well and deprecate it and ignore the second argument ?", "final ?", "?", "Whatever you prefer ", "Done.", "It was a bug. `goAwayMax` wasn't used when it should have been. Fixed.", "Done. This had been public in my changes until the last minute. Oops.", "Unclear how many people are using that, but sure. It's easy. Done.", "I don't tend to put `final` on private classes, but sure. Done." ]
"2018-05-06T20:03:11Z"
[ "improvement" ]
HpackDecoder's maxHeaderListSizeGoAway kills stream unnecessarily
Consider this a bit of a TODO for myself, although @Scottmitch or @normanmaurer may have opinions about avoiding killing the connection in this case. ### Expected behavior Sending too large of headers would not unnecessarily kill the connection. ### Actual behavior When maxHeaderListSizeGoAway is exceeded, HpackDecoder will throw a connection error, killing the entire connection. ``` // Check new header size against max header size if ((long) index + nameLength > maxHeaderListSizeGoAway - headersLength) { headerListSizeExceeded(maxHeaderListSizeGoAway); } ``` Note, I'm not talking about the separate check later against maxHeaderListSize and throws a _stream_ error: ``` // we have read all of our headers, and not exceeded maxHeaderListSizeGoAway see if we have // exceeded our actual maxHeaderListSize. This must be done here to prevent dynamic table // corruption if (headersLength > maxHeaderListSize) { headerListSizeExceeded(streamId, maxHeaderListSize, true); } ``` Even though both of those call `headerListSizeExceeded()`, they call different overloads of the method which will throw different types of exceptions (connection vs stream). The value of maxHeaderListSizeGoAway is likely 1.25 the size of maxHeaderListSize, although I see there's some ways it could be something different and I didn't dig in more. This killing of the connection seems unnecessary though, as: 1) It seems it would be pretty easy to throw away this batch of headers, by setting `headers` to a `Http2Headers` implementation that throws away further adds (similar complexity to `EmptyHttp2Headers`). This could be done any time `headersLength > maxHeaderListSize`. 2) When decode is called, the "entire header block is contained in {@code in}". So this protection doesn't protect us from buffering any more data; it only reduced the decoded headers size. That is, throwing away decoded headers as suggested in (1) does not seem to expose us to other problems. Note also there are separate checks in `DefaultHttp2FrameReader.HeadersBlockBuilder` that protect against too large of compressed HEADERS+CONTINUATION. This is what constrains the size of `in`.
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java index 684fef03528..5d6320950ca 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoder.java @@ -22,6 +22,7 @@ import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_HEADER_LIST_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_INITIAL_HUFFMAN_DECODE_CAPACITY; import static io.netty.handler.codec.http2.Http2Error.COMPRESSION_ERROR; +import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR; import static io.netty.handler.codec.http2.Http2Exception.connectionError; @UnstableApi @@ -31,6 +32,7 @@ public class DefaultHttp2HeadersDecoder implements Http2HeadersDecoder, Http2Hea private final HpackDecoder hpackDecoder; private final boolean validateHeaders; + private long maxHeaderListSizeGoAway; /** * Used to calculate an exponential moving average of header sizes to get an estimate of how large the data @@ -79,6 +81,8 @@ public DefaultHttp2HeadersDecoder(boolean validateHeaders, long maxHeaderListSiz DefaultHttp2HeadersDecoder(boolean validateHeaders, HpackDecoder hpackDecoder) { this.hpackDecoder = ObjectUtil.checkNotNull(hpackDecoder, "hpackDecoder"); this.validateHeaders = validateHeaders; + this.maxHeaderListSizeGoAway = + Http2CodecUtil.calculateMaxHeaderListSizeGoAway(hpackDecoder.getMaxHeaderListSize()); } @Override @@ -93,7 +97,12 @@ public long maxHeaderTableSize() { @Override public void maxHeaderListSize(long max, long goAwayMax) throws Http2Exception { - hpackDecoder.setMaxHeaderListSize(max, goAwayMax); + if (goAwayMax < max || goAwayMax < 0) { + throw connectionError(INTERNAL_ERROR, "Header List Size GO_AWAY %d must be non-negative and >= %d", + goAwayMax, max); + } + hpackDecoder.setMaxHeaderListSize(max); + this.maxHeaderListSizeGoAway = goAwayMax; } @Override @@ -103,7 +112,7 @@ public long maxHeaderListSize() { @Override public long maxHeaderListSizeGoAway() { - return hpackDecoder.getMaxHeaderListSizeGoAway(); + return maxHeaderListSizeGoAway; } @Override diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java index 67d6aa9944b..078c0798918 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackDecoder.java @@ -42,7 +42,6 @@ import static io.netty.handler.codec.http2.Http2CodecUtil.MIN_HEADER_TABLE_SIZE; import static io.netty.handler.codec.http2.Http2CodecUtil.headerListSizeExceeded; import static io.netty.handler.codec.http2.Http2Error.COMPRESSION_ERROR; -import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR; import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR; import static io.netty.handler.codec.http2.Http2Exception.connectionError; import static io.netty.handler.codec.http2.Http2Headers.PseudoHeaderName.getPseudoHeader; @@ -84,7 +83,6 @@ final class HpackDecoder { private final HpackDynamicTable hpackDynamicTable; private final HpackHuffmanDecoder hpackHuffmanDecoder; - private long maxHeaderListSizeGoAway; private long maxHeaderListSize; private long maxDynamicTableSize; private long encoderMaxDynamicTableSize; @@ -108,7 +106,6 @@ final class HpackDecoder { */ HpackDecoder(long maxHeaderListSize, int initialHuffmanDecodeCapacity, int maxHeaderTableSize) { this.maxHeaderListSize = checkPositive(maxHeaderListSize, "maxHeaderListSize"); - this.maxHeaderListSizeGoAway = Http2CodecUtil.calculateMaxHeaderListSizeGoAway(maxHeaderListSize); maxDynamicTableSize = encoderMaxDynamicTableSize = maxHeaderTableSize; maxDynamicTableSizeChangeRequired = false; @@ -122,8 +119,18 @@ final class HpackDecoder { * This method assumes the entire header block is contained in {@code in}. */ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { + Http2HeadersSink sink = new Http2HeadersSink(headers, maxHeaderListSize); + decode(in, sink, validateHeaders); + + // we have read all of our headers. See if we have exceeded our maxHeaderListSize. We must + // delay throwing until this point to prevent dynamic table corruption + if (sink.exceededMaxLength()) { + headerListSizeExceeded(streamId, maxHeaderListSize, true); + } + } + + private void decode(ByteBuf in, Sink sink, boolean validateHeaders) throws Http2Exception { int index = 0; - long headersLength = 0; int nameLength = 0; int valueLength = 0; byte state = READ_HEADER_REPRESENTATION; @@ -151,8 +158,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid default: HpackHeaderField indexedHeader = getIndexedHeader(index); headerType = validate(indexedHeader.name, headerType, validateHeaders); - headersLength = addHeader(headers, indexedHeader.name, indexedHeader.value, - headersLength); + sink.appendToHeaderList(indexedHeader.name, indexedHeader.value); } } else if ((b & 0x40) == 0x40) { // Literal Header Field with Incremental Indexing @@ -193,11 +199,11 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid state = READ_INDEXED_HEADER_NAME; break; default: - // Index was stored as the prefix - name = readName(index); + // Index was stored as the prefix + name = readName(index); headerType = validate(name, headerType, validateHeaders); - nameLength = name.length(); - state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; + nameLength = name.length(); + state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX; } } break; @@ -210,7 +216,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid case READ_INDEXED_HEADER: HpackHeaderField indexedHeader = getIndexedHeader(decodeULE128(in, index)); headerType = validate(indexedHeader.name, headerType, validateHeaders); - headersLength = addHeader(headers, indexedHeader.name, indexedHeader.value, headersLength); + sink.appendToHeaderList(indexedHeader.name, indexedHeader.value); state = READ_HEADER_REPRESENTATION; break; @@ -229,9 +235,6 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid if (index == 0x7f) { state = READ_LITERAL_HEADER_NAME_LENGTH; } else { - if (index > maxHeaderListSizeGoAway - headersLength) { - headerListSizeExceeded(maxHeaderListSizeGoAway); - } nameLength = index; state = READ_LITERAL_HEADER_NAME; } @@ -241,9 +244,6 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid // Header Name is a Literal String nameLength = decodeULE128(in, index); - if (nameLength > maxHeaderListSizeGoAway - headersLength) { - headerListSizeExceeded(maxHeaderListSizeGoAway); - } state = READ_LITERAL_HEADER_NAME; break; @@ -269,14 +269,10 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid break; case 0: headerType = validate(name, headerType, validateHeaders); - headersLength = insertHeader(headers, name, EMPTY_STRING, indexType, headersLength); + insertHeader(sink, name, EMPTY_STRING, indexType); state = READ_HEADER_REPRESENTATION; break; default: - // Check new header size against max header size - if ((long) index + nameLength > maxHeaderListSizeGoAway - headersLength) { - headerListSizeExceeded(maxHeaderListSizeGoAway); - } valueLength = index; state = READ_LITERAL_HEADER_VALUE; } @@ -287,10 +283,6 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid // Header Value is a Literal String valueLength = decodeULE128(in, index); - // Check new header size against max header size - if ((long) valueLength + nameLength > maxHeaderListSizeGoAway - headersLength) { - headerListSizeExceeded(maxHeaderListSizeGoAway); - } state = READ_LITERAL_HEADER_VALUE; break; @@ -302,7 +294,7 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid CharSequence value = readStringLiteral(in, valueLength, huffmanEncoded); headerType = validate(name, headerType, validateHeaders); - headersLength = insertHeader(headers, name, value, indexType, headersLength); + insertHeader(sink, name, value, indexType); state = READ_HEADER_REPRESENTATION; break; @@ -311,13 +303,6 @@ public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean valid } } - // we have read all of our headers, and not exceeded maxHeaderListSizeGoAway see if we have - // exceeded our actual maxHeaderListSize. This must be done here to prevent dynamic table - // corruption - if (headersLength > maxHeaderListSize) { - headerListSizeExceeded(streamId, maxHeaderListSize, true); - } - if (state != READ_HEADER_REPRESENTATION) { throw connectionError(COMPRESSION_ERROR, "Incomplete header block fragment."); } @@ -341,27 +326,27 @@ public void setMaxHeaderTableSize(long maxHeaderTableSize) throws Http2Exception } } + /** + * @deprecated use {@link #setmaxHeaderListSize(long)}; {@code maxHeaderListSizeGoAway} is + * ignored + */ + @Deprecated public void setMaxHeaderListSize(long maxHeaderListSize, long maxHeaderListSizeGoAway) throws Http2Exception { - if (maxHeaderListSizeGoAway < maxHeaderListSize || maxHeaderListSizeGoAway < 0) { - throw connectionError(INTERNAL_ERROR, "Header List Size GO_AWAY %d must be positive and >= %d", - maxHeaderListSizeGoAway, maxHeaderListSize); - } + setMaxHeaderListSize(maxHeaderListSize); + } + + public void setMaxHeaderListSize(long maxHeaderListSize) throws Http2Exception { if (maxHeaderListSize < MIN_HEADER_LIST_SIZE || maxHeaderListSize > MAX_HEADER_LIST_SIZE) { throw connectionError(PROTOCOL_ERROR, "Header List Size must be >= %d and <= %d but was %d", MIN_HEADER_TABLE_SIZE, MAX_HEADER_TABLE_SIZE, maxHeaderListSize); } this.maxHeaderListSize = maxHeaderListSize; - this.maxHeaderListSizeGoAway = maxHeaderListSizeGoAway; } public long getMaxHeaderListSize() { return maxHeaderListSize; } - public long getMaxHeaderListSizeGoAway() { - return maxHeaderListSizeGoAway; - } - /** * Return the maximum table size. This is the maximum size allowed by both the encoder and the * decoder. @@ -450,9 +435,9 @@ private HpackHeaderField getIndexedHeader(int index) throws Http2Exception { throw INDEX_HEADER_ILLEGAL_INDEX_VALUE; } - private long insertHeader(Http2Headers headers, CharSequence name, CharSequence value, - IndexType indexType, long headerSize) throws Http2Exception { - headerSize = addHeader(headers, name, value, headerSize); + private void insertHeader(Sink sink, CharSequence name, CharSequence value, + IndexType indexType) throws Http2Exception { + sink.appendToHeaderList(name, value); switch (indexType) { case NONE: @@ -466,18 +451,6 @@ private long insertHeader(Http2Headers headers, CharSequence name, CharSequence default: throw new Error("should not reach here"); } - - return headerSize; - } - - private long addHeader(Http2Headers headers, CharSequence name, CharSequence value, long headersLength) - throws Http2Exception { - headersLength += HpackHeaderField.sizeOf(name, value); - if (headersLength > maxHeaderListSizeGoAway) { - headerListSizeExceeded(maxHeaderListSizeGoAway); - } - headers.add(name, value); - return headersLength; } private CharSequence readStringLiteral(ByteBuf in, int length, boolean huffmanEncoded) throws Http2Exception { @@ -553,4 +526,35 @@ private enum HeaderType { REQUEST_PSEUDO_HEADER, RESPONSE_PSEUDO_HEADER } + + private interface Sink { + void appendToHeaderList(CharSequence name, CharSequence value); + } + + private static final class Http2HeadersSink implements Sink { + private final Http2Headers headers; + private final long maxHeaderListSize; + private long headersLength; + private boolean exceededMaxLength; + + public Http2HeadersSink(Http2Headers headers, long maxHeaderListSize) { + this.headers = headers; + this.maxHeaderListSize = maxHeaderListSize; + } + + @Override + public void appendToHeaderList(CharSequence name, CharSequence value) { + headersLength += HpackHeaderField.sizeOf(name, value); + if (headersLength > maxHeaderListSize) { + exceededMaxLength = true; + } + if (!exceededMaxLength) { + headers.add(name, value); + } + } + + public boolean exceededMaxLength() { + return exceededMaxLength; + } + } }
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java index 4652a1fceb6..ba0117553eb 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.java @@ -431,15 +431,13 @@ public void testLiteralNeverIndexedWithLargeValue() throws Http2Exception { } @Test - public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSizeUpdatesDynamicTable() - throws Http2Exception { + public void testDecodeLargerThanMaxHeaderListSizeUpdatesDynamicTable() throws Http2Exception { ByteBuf in = Unpooled.buffer(300); try { - hpackDecoder.setMaxHeaderListSize(200, 300); + hpackDecoder.setMaxHeaderListSize(200); HpackEncoder hpackEncoder = new HpackEncoder(true); // encode headers that are slightly larger than maxHeaderListSize - // but smaller than maxHeaderListSizeGoAway Http2Headers toEncode = new DefaultHttp2Headers(); toEncode.add("test_1", "1"); toEncode.add("test_2", "2"); @@ -447,8 +445,7 @@ public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSize toEncode.add("test_3", "3"); hpackEncoder.encodeHeaders(1, in, toEncode, NEVER_SENSITIVE); - // decode the headers, we should get an exception, but - // the decoded headers object should contain all of the headers + // decode the headers, we should get an exception Http2Headers decoded = new DefaultHttp2Headers(); try { hpackDecoder.decode(1, in, decoded, true); @@ -457,8 +454,18 @@ public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSize assertTrue(e instanceof Http2Exception.HeaderListSizeException); } - assertEquals(4, decoded.size()); - assertTrue(decoded.contains("test_3")); + // but the dynamic table should have been updated, so that later blocks + // can refer to earlier headers + in.clear(); + // 0x80, "indexed header field representation" + // index 62, the first (most recent) dynamic table entry + in.writeByte(0x80 | 62); + Http2Headers decoded2 = new DefaultHttp2Headers(); + hpackDecoder.decode(1, in, decoded2, true); + + Http2Headers golden = new DefaultHttp2Headers(); + golden.add("test_3", "3"); + assertEquals(golden, decoded2); } finally { in.release(); } @@ -468,11 +475,10 @@ public void testDecodeLargerThanMaxHeaderListSizeButSmallerThanMaxHeaderListSize public void testDecodeCountsNamesOnlyOnce() throws Http2Exception { ByteBuf in = Unpooled.buffer(200); try { - hpackDecoder.setMaxHeaderListSize(3500, 4000); + hpackDecoder.setMaxHeaderListSize(3500); HpackEncoder hpackEncoder = new HpackEncoder(true); // encode headers that are slightly larger than maxHeaderListSize - // but smaller than maxHeaderListSizeGoAway Http2Headers toEncode = new DefaultHttp2Headers(); toEncode.add(String.format("%03000d", 0).replace('0', 'f'), "value"); toEncode.add("accept", "value"); @@ -493,7 +499,7 @@ public void testAccountForHeaderOverhead() throws Exception { String headerName = "12345"; String headerValue = "56789"; long headerSize = headerName.length() + headerValue.length(); - hpackDecoder.setMaxHeaderListSize(headerSize, 100); + hpackDecoder.setMaxHeaderListSize(headerSize); HpackEncoder hpackEncoder = new HpackEncoder(true); Http2Headers toEncode = new DefaultHttp2Headers(); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java index b1dce05c38b..de049a6e506 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java @@ -74,7 +74,7 @@ public void testWillEncode16MBHeaderByDefault() throws Http2Exception { try { hpackEncoder.encodeHeaders(0, buf, headersIn, Http2HeadersEncoder.NEVER_SENSITIVE); - hpackDecoder.setMaxHeaderListSize(bigHeaderSize + 1024, bigHeaderSize + 1024); + hpackDecoder.setMaxHeaderListSize(bigHeaderSize + 1024); hpackDecoder.decode(0, buf, headersOut, false); } finally { buf.release();
val
val
"2018-05-15T11:38:15"
"2018-04-24T22:12:21Z"
ejona86
val
netty/netty/7901_7927
netty/netty
netty/netty/7901
netty/netty/7927
[ "timestamp(timedelta=0.0, similarity=0.8400210261055583)" ]
dc0cf3e099a8f1f4a74cbf114afabaa5ba3eee4f
583fc272f26373ff5f51c0871d9730370cd39a3e
[]
[]
"2018-05-11T19:54:37Z"
[]
Netty Client concurrent issue when close FixedChannelPool
I use Netty as A tcp Client, use FixedChannelPool as channelPool. when Close client,some time will cause follow exception ### Expected behavior no exception ### Actual behavior ```text [xxxxxx]2018-04-03 14:34:56 04 [io.netty.util.concurrent.DefaultPromise.rejectedExecution]-[ERROR] Failed to submit a listener notification task. Event loop shut down? java.util.concurrent.RejectedExecutionException: event executor terminated at io.netty.util.concurrent.SingleThreadEventExecutor.reject(SingleThreadEventExecutor.java:821) at io.netty.util.concurrent.SingleThreadEventExecutor.offerTask(SingleThreadEventExecutor.java:327) at io.netty.util.concurrent.SingleThreadEventExecutor.addTask(SingleThreadEventExecutor.java:320) at io.netty.util.concurrent.SingleThreadEventExecutor.execute(SingleThreadEventExecutor.java:746) at io.netty.util.concurrent.DefaultPromise.safeExecute(DefaultPromise.java:760) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:428) at io.netty.util.concurrent.DefaultPromise.setFailure(DefaultPromise.java:113) at io.netty.channel.DefaultChannelPromise.setFailure(DefaultChannelPromise.java:87) at io.netty.channel.AbstractChannelHandlerContext.safeExecute(AbstractChannelHandlerContext.java:1010) at io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:610) at io.netty.channel.AbstractChannelHandlerContext.close(AbstractChannelHandlerContext.java:465) at io.netty.channel.DefaultChannelPipeline.close(DefaultChannelPipeline.java:972) at io.netty.channel.AbstractChannel.close(AbstractChannel.java:234) at io.netty.channel.pool.SimpleChannelPool.close(SimpleChannelPool.java:397) at io.netty.channel.pool.FixedChannelPool.access$1201(FixedChannelPool.java:38) at io.netty.channel.pool.FixedChannelPool$5.run(FixedChannelPool.java:458) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463 at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) at java.lang.Thread.run(Thread.java:745) ``` ### Steps to reproduce my client code ```java public void init() { ioGroup = new NioEventLoopGroup(ioThreadCnt, new DefaultThreadFactory("mainstay-ioNioEventLoopGroup" + "-" + getUrl().getGroup())); bootstrap.group(ioGroup).channel(SocketChannel); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, reqConnTimeout); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)); bootstrap.remoteAddress(new InetSocketAddress(remoteIp, port)); fixedChannelPool = new FixedChannelPool(bootstrap, nettyClientChannelPoolHandler, channelHealthChecker, FixedChannelPool.AcquireTimeoutAction.FAIL, 2000, 1000, 100, false, false); } public void close() { fixedChannelPool.close(); if (ioGroup != null) { io.netty.util.concurrent.Future shutownfuture = ioGroup.shutdownGracefully(4, 32, TimeUnit.SECONDS); try { shutownfuture.get(64L, TimeUnit.SECONDS); } catch (Throwable e) { LOG.error("wait shutdown gracefully more than 64 second!", e); } } } ``` my netty client runs well after init(), but when call `close()`,maybe cause `rejectedExecution` Exception, and this exception is not appear every time when call `close()`. This Exception happend probability is low ,may be lower than 5% ### my solution This is because, fixedChannelPool.close actually submit close Task to Threadpool, is async. so maybe ioGroup will be closed before. If i add some sleep after `fixedChannelPool.close` will also reduce exception happend probability. but may still happened. ``` fixedChannelPool.close(); Thread.sleep(1500); // ioGroup.close ... ``` how about `fixedChannelPool.close` return a Future, or make do not make it run in executor, make it run synchronized. ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.14.Final ### JVM version (e.g. `java -version`) java 1.6-1.8 ### OS version (e.g. `uname -a`) Linux node2.live 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
[ "transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java", "transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java" ]
[ "transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java", "transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java b/transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java index 1c0ebcc5343..16a8a7cc9a7 100644 --- a/transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java +++ b/transport/src/main/java/io/netty/channel/pool/FixedChannelPool.java @@ -20,6 +20,7 @@ import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; +import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.ThrowableUtil; @@ -437,27 +438,43 @@ public void acquired() { @Override public void close() { - executor.execute(new Runnable() { - @Override - public void run() { - if (!closed) { - closed = true; - for (;;) { - AcquireTask task = pendingAcquireQueue.poll(); - if (task == null) { - break; - } - ScheduledFuture<?> f = task.timeoutFuture; - if (f != null) { - f.cancel(false); - } - task.promise.setFailure(new ClosedChannelException()); - } - acquiredChannelCount = 0; - pendingAcquireCount = 0; - FixedChannelPool.super.close(); + if (executor.inEventLoop()) { + close0(); + } else { + executor.submit(new Runnable() { + @Override + public void run() { + close0(); + } + }).awaitUninterruptibly(); + } + } + + private void close0() { + if (!closed) { + closed = true; + for (;;) { + AcquireTask task = pendingAcquireQueue.poll(); + if (task == null) { + break; + } + ScheduledFuture<?> f = task.timeoutFuture; + if (f != null) { + f.cancel(false); } + task.promise.setFailure(new ClosedChannelException()); } - }); + acquiredChannelCount = 0; + pendingAcquireCount = 0; + + // Ensure we dispatch this on another Thread as close0 will be called from the EventExecutor and we need + // to ensure we will not block in a EventExecutor. + GlobalEventExecutor.INSTANCE.execute(new Runnable() { + @Override + public void run() { + FixedChannelPool.super.close(); + } + }); + } } } diff --git a/transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java b/transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java index d8dd0eae940..6fcfd4443fa 100644 --- a/transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java +++ b/transport/src/main/java/io/netty/channel/pool/SimpleChannelPool.java @@ -394,7 +394,8 @@ public void close() { if (channel == null) { break; } - channel.close(); + // Just ignore any errors that are reported back from close(). + channel.close().awaitUninterruptibly(); } } }
null
val
val
"2018-05-12T20:25:11"
"2018-04-30T10:22:27Z"
caorong
val
netty/netty/7954_7955
netty/netty
netty/netty/7954
netty/netty/7955
[ "timestamp(timedelta=0.0, similarity=0.866942814981692)" ]
583fc272f26373ff5f51c0871d9730370cd39a3e
19d1f4ea628d5042ea93856d286cb31b453beda0
[ "@nicktrav actually I think the idea was that usually PONG frames should be dropped on the floor. That said I would argue that is not the best thing to do \"magically\" and it may be better to let the user decide to drop it or not. So maybe we should not do this ?", "Yeah, that would be awesome for us. Principle of least surprise, etc, etc.\r\n\r\nI might take a crack at this one, if that's cool? I was thinking I'd just remove those lines so the frames are propagated, and I'll add a couple tests for it in the server and client handler subclasses. Wdyt?", "yeah... please :)", "@normanmaurer wouldn't this cause regression? Maybe making `decode` method of `WebSocketServerProtocolHandler` public would be enough, so users can override this behavior?", "@doom369 I think we should just do what @trustin suggested in the PR and make it configurable and use the old behaviour as default.", "@nicktrav , @normanmaurer In our case we extend ``WebSocketServerProtocolHandler`` and override decode() for handling pong and close frames, but we can add some handler before ``WebSocketServerProtocolHandler`` and listen all web socket frames. Maybe in downstream handler anybody want listen close frame ??? " ]
[ "assert return value please", "assert return value please", "assert return value please", "You can use use `Unpooled.copiedBuffer(...)` to simplify this a bit.", "Call `channel.finish()` and assert return value", "Call `channel.finish()` and assert return value", "Call `channel.finish()` and assert return value", "Use `CharsetUtil.UTF_8`", "@normanmaurer I would suggest flipping the conditions, boolean is cheaper than instance of. ", "@johnou I thought so as well when review but then just assumed it will be optimised any way as the JIT will know `dropPongFrames` will never change and so can just optimise the branch.", "so to make it short I think it not matters.", ":+1: makes sense " ]
"2018-05-18T20:49:01Z"
[]
PongWebSocketFrames are inaccessible in handlers downstream of a WebSocketClientProtocolHandler
This is probably more of a question / request rather than a bug, as it looks like this was a deliberate decision ([source](https://github.com/netty/netty/blob/netty-4.1.25.Final/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java#L32-L35)). The use-case is a handler being able to assert that a pong frame was received from a Netty-based proxy server. ### Expected behavior `PongWebSocketFrame`s are visible to a channel handler installed _downstream_ of a `WebSocketClientProtocolHandler`. ### Actual behavior Sending a `PingWebSocketFrame` from a client to a server results in receipt of a `PongWebSocketFrame` by the client in the `WebSocketClientProtocolHandler`, but this frame is not propagated further along the channel pipeline. ### Steps to reproduce I've pushed a commit [here](https://github.com/nicktrav/netty/commit/4cae21eb36fe873d24073e730cbda9bb1994741b) which demonstrates the issue. ### Minimal yet complete reproducer code (or URL to code) Check out commit and run: ```bash $ mvn test -pl codec-http -Dtest=io.netty.handler.codec.http.websocketx.PongFrameIgnoreTest ``` ### Netty version `4.1.25.Final`. Also run against `HEAD` of `4.1` branch @ 987c44388. ### JVM version (e.g. `java -version`) ```bash $ java -version java version "10.0.1" 2018-04-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode) ``` ### OS version (e.g. `uname -a`) ```bash $ uname -a Darwin nickt.local 17.3.0 Darwin Kernel Version 17.3.0: Thu Nov 9 18:09:22 PST 2017; root:xnu-4570.31.3~1/RELEASE_X86_64 x86_64 ```
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandlerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java index 2ace7e8aa09..7c85c57748d 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java @@ -151,6 +151,23 @@ public WebSocketClientProtocolHandler(URI webSocketURL, WebSocketVersion version * {@code true} if close frames should not be forwarded and just close the channel */ public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker, boolean handleCloseFrames) { + this(handshaker, handleCloseFrames, true); + } + + /** + * Base constructor + * + * @param handshaker + * The {@link WebSocketClientHandshaker} which will be used to issue the handshake once the connection + * was established to the remote peer. + * @param handleCloseFrames + * {@code true} if close frames should not be forwarded and just close the channel + * @param dropPongFrames + * {@code true} if pong frames should not be forwarded + */ + public WebSocketClientProtocolHandler(WebSocketClientHandshaker handshaker, boolean handleCloseFrames, + boolean dropPongFrames) { + super(dropPongFrames); this.handshaker = handshaker; this.handleCloseFrames = handleCloseFrames; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java index 7037ae34686..53532cafe98 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandler.java @@ -22,6 +22,27 @@ import java.util.List; abstract class WebSocketProtocolHandler extends MessageToMessageDecoder<WebSocketFrame> { + + private final boolean dropPongFrames; + + /** + * Creates a new {@link WebSocketProtocolHandler} that will <i>drop</i> {@link PongWebSocketFrame}s. + */ + WebSocketProtocolHandler() { + this(true); + } + + /** + * Creates a new {@link WebSocketProtocolHandler}, given a parameter that determines whether or not to drop {@link + * PongWebSocketFrame}s. + * + * @param dropPongFrames + * {@code true} if {@link PongWebSocketFrame}s should be dropped + */ + WebSocketProtocolHandler(boolean dropPongFrames) { + this.dropPongFrames = dropPongFrames; + } + @Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception { if (frame instanceof PingWebSocketFrame) { @@ -29,8 +50,7 @@ protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Obje ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content())); return; } - if (frame instanceof PongWebSocketFrame) { - // Pong frames need to get ignored + if (frame instanceof PongWebSocketFrame && dropPongFrames) { return; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java index 6b5ef13af53..3a19b145426 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerProtocolHandler.java @@ -132,6 +132,13 @@ public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch, boolean checkStartsWith) { + this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, checkStartsWith, true); + } + + public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, + boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch, + boolean checkStartsWith, boolean dropPongFrames) { + super(dropPongFrames); this.websocketPath = websocketPath; this.subprotocols = subprotocols; this.allowExtensions = allowExtensions;
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandlerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandlerTest.java new file mode 100644 index 00000000000..af7498222ce --- /dev/null +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketProtocolHandlerTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package io.netty.handler.codec.http.websocketx; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.util.CharsetUtil; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests common, abstract class functionality in {@link WebSocketClientProtocolHandler}. + */ +public class WebSocketProtocolHandlerTest { + + @Test + public void testPingFrame() { + ByteBuf pingData = Unpooled.copiedBuffer("Hello, world", CharsetUtil.UTF_8); + EmbeddedChannel channel = new EmbeddedChannel(new WebSocketProtocolHandler() { }); + + PingWebSocketFrame inputMessage = new PingWebSocketFrame(pingData); + assertFalse(channel.writeInbound(inputMessage)); // the message was not propagated inbound + + // a Pong frame was written to the channel + PongWebSocketFrame response = channel.readOutbound(); + assertEquals(pingData, response.content()); + + pingData.release(); + assertFalse(channel.finish()); + } + + @Test + public void testPongFrameDropFrameFalse() { + EmbeddedChannel channel = new EmbeddedChannel(new WebSocketProtocolHandler(false) { }); + + PongWebSocketFrame pingResponse = new PongWebSocketFrame(); + assertTrue(channel.writeInbound(pingResponse)); + + assertPropagatedInbound(pingResponse, channel); + + pingResponse.release(); + assertFalse(channel.finish()); + } + + @Test + public void testPongFrameDropFrameTrue() { + EmbeddedChannel channel = new EmbeddedChannel(new WebSocketProtocolHandler(true) { }); + + PongWebSocketFrame pingResponse = new PongWebSocketFrame(); + assertFalse(channel.writeInbound(pingResponse)); // message was not propagated inbound + } + + @Test + public void testTextFrame() { + EmbeddedChannel channel = new EmbeddedChannel(new WebSocketProtocolHandler() { }); + + TextWebSocketFrame textFrame = new TextWebSocketFrame(); + assertTrue(channel.writeInbound(textFrame)); + + assertPropagatedInbound(textFrame, channel); + + textFrame.release(); + assertFalse(channel.finish()); + } + + /** + * Asserts that a message was propagated inbound through the channel. + */ + private static <T extends WebSocketFrame> void assertPropagatedInbound(T message, EmbeddedChannel channel) { + T propagatedResponse = channel.readInbound(); + assertEquals(message, propagatedResponse); + } +}
train
val
"2018-05-21T19:22:31"
"2018-05-18T18:42:56Z"
nicktrav
val
netty/netty/7964_7965
netty/netty
netty/netty/7964
netty/netty/7965
[ "timestamp(timedelta=0.0, similarity=0.8595601789507803)" ]
583fc272f26373ff5f51c0871d9730370cd39a3e
4d6b006fe64059b6b9eba9fbb835dc4a22d33393
[ "sounds like a bug to me... looking now", "@ewie thanks for reporting, fixed by https://github.com/netty/netty/pull/7965" ]
[ "Assert the hash codes are equal as well." ]
"2018-05-24T06:03:19Z"
[]
DefaultHttpResponse does not implement equals and hashCode to cover response status
### Expected behavior Two DefaultHttpResponse instances with different response status should not be considered equal. Headers and HTTP version are already covered in DefaultHttpMessage. DefaultFullHttpResponse also covers content and trailing headers. I would assume the response status is considered as well. ### Actual behavior Response status is ignored by equals and hashCode. DefaultHttpResponse does not override those methods. ### Steps to reproduce Run example below. ### Minimal yet complete reproducer code ```java import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; class ResponseStatusEquality { public static void main(String... args) { var ok = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); var notFound = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); if (ok.equals(notFound)) { throw new AssertionError(); // should not throw! } } } ``` ### Netty version 4.1.25.Final ### JVM version (e.g. `java -version`) openjdk version "10.0.1" 2018-04-17 OpenJDK Runtime Environment (build 10.0.1+10) OpenJDK 64-Bit Server VM (build 10.0.1+10, mixed mode) ### OS version (e.g. `uname -a`) Linux 4.16.10
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpResponseTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java index 86858108a27..d5b7cf0b7b9 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/DefaultHttpResponse.java @@ -105,4 +105,23 @@ public HttpResponse setProtocolVersion(HttpVersion version) { public String toString() { return HttpMessageUtil.appendResponse(new StringBuilder(256), this).toString(); } + + @Override + public int hashCode() { + int result = 1; + result = 31 * result + status.hashCode(); + result = 31 * result + super.hashCode(); + return result; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof DefaultHttpResponse)) { + return false; + } + + DefaultHttpResponse other = (DefaultHttpResponse) o; + + return status.equals(other.status()) && super.equals(o); + } }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpResponseTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpResponseTest.java new file mode 100644 index 00000000000..0a466c6bff9 --- /dev/null +++ b/codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpResponseTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2018 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package io.netty.handler.codec.http; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +public class DefaultHttpResponseTest { + + @Test + public void testNotEquals() { + HttpResponse ok = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); + HttpResponse notFound = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); + assertNotEquals(ok, notFound); + assertNotEquals(ok.hashCode(), notFound.hashCode()); + } + + @Test + public void testEquals() { + HttpResponse ok = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); + HttpResponse ok2 = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); + assertEquals(ok, ok2); + assertEquals(ok.hashCode(), ok2.hashCode()); + } +}
val
val
"2018-05-21T19:22:31"
"2018-05-24T00:25:56Z"
ewie
val