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/12445_12467
netty/netty
netty/netty/12445
netty/netty/12467
[ "keyword_pr_to_issue" ]
c18fc2bc68c08805b2553336a3bf02f0c8c50972
7971075bbe9f5509c8b20c0e702ec2affb37d76e
[ "Do you want to make a PR?" ]
[]
"2022-06-14T12:39:00Z"
[]
FlowControlHandler breaks auto-reading
_FlowControlHandler_ breaks auto-reading (i.e. the channel does not auto-read even though its config has auto-read set to true). This happens when auto-read is turned on when the queue is not empty. The reason is that _FlowControlHandler.read()_ does not pass the call to the _ChannelHandlerContext_ if at least one message has been dequeued. This is a problem when _FlowControlHandler.read()_ has been called as a result of auto-read having been turned on (_DefaultChannelConfig.setAutoRead()_ calling read() in case of _autoRead && !oldAutoRead_). Taking _ctx.read();_ out of the body of the if statement fixes the bug and I also did not notice any unwanted side effects. I.e.: ``` public void read(ChannelHandlerContext ctx) throws Exception { if (dequeue(ctx, 1) == 0) { shouldConsume = true; } ctx.read(); } ``` ### Expected behavior Auto-reading. ### Actual behavior Reading the messages that are already in the queue and then no auto-reading. ### Steps to reproduce On a channel with a FlowControlHandler in its pipeline, turn auto-read off while a message is in the process of being added to the handler's queue. When the message is already in the queue, turn auto-read back on. ### Minimal yet complete reproducer code (or URL to code) It is a bit hard to reproduce with simple code so I hope that you understand the issue from my description. ### Netty version any ### JVM version (e.g. `java -version`) any ### OS version (e.g. `uname -a`) any
[ "handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java" ]
[ "handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java index 1f7926fdf2f..f316907a7e5 100644 --- a/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java +++ b/handler/src/main/java/io/netty/handler/flow/FlowControlHandler.java @@ -141,8 +141,8 @@ public void read(ChannelHandlerContext ctx) throws Exception { // messages from upstream and once one arrives it need to be // relayed to downstream to keep the flow going. shouldConsume = true; - ctx.read(); } + ctx.read(); } @Override
null
test
test
"2022-06-13T08:44:56"
"2022-06-06T17:15:26Z"
gbrdead
val
netty/netty/12480_12483
netty/netty
netty/netty/12480
netty/netty/12483
[ "keyword_pr_to_issue" ]
b063c211277fcfb4453f24aad3bda8529cf21b8a
f43a9dd0a384eb6226e31648b7168e4fa241527d
[ "These are used by the native code loading. I think it'd be better to have a system property where the classifier set can be directly specified, and then avoid reading the files if that property is present. Then it could also serve a dual purpose of overriding the files in case they produce a wrong classifier set for some reason." ]
[]
"2022-06-17T15:31:45Z"
[]
Opt-out from blocking reads of OS files for classifiers
### Expected behavior Less of redundant blocking IO in netty ### Actual behavior On initialization netty does [blocking](https://github.com/netty/netty/blob/c87c911c010c3a34a69e550d52299df20e5fc740/common/src/main/java/io/netty/util/internal/PlatformDependent.java#L231) reads of `/etc/os-release`, `/usr/lib/os-release` for specific classifiers that are never available on some popular distros (e.g. ubuntu, alpine). It would be helpful to avoid such blocking calls with system property - e.g. `-Dio.netty.readOsClassifiers=false`. ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.78.Final ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "common/src/main/java/io/netty/util/internal/PlatformDependent.java" ]
[ "common/src/main/java/io/netty/util/internal/PlatformDependent.java" ]
[ "common/src/test/java/io/netty/util/internal/OsClassifiersTest.java" ]
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 00310e585ea..cfa61f60406 100644 --- a/common/src/main/java/io/netty/util/internal/PlatformDependent.java +++ b/common/src/main/java/io/netty/util/internal/PlatformDependent.java @@ -219,6 +219,15 @@ public Random current() { final Set<String> allowedClassifiers = Collections.unmodifiableSet( new HashSet<String>(Arrays.asList(ALLOWED_LINUX_OS_CLASSIFIERS))); final Set<String> availableClassifiers = new LinkedHashSet<String>(); + + if (!addPropertyOsClassifiers(allowedClassifiers, availableClassifiers)) { + addFilesystemOsClassifiers(allowedClassifiers, availableClassifiers); + } + LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers); + } + + static void addFilesystemOsClassifiers(final Set<String> allowedClassifiers, + final Set<String> availableClassifiers) { for (final String osReleaseFileName : OS_RELEASE_FILES) { final File file = new File(osReleaseFileName); boolean found = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { @@ -271,7 +280,37 @@ public Boolean run() { break; } } - LINUX_OS_CLASSIFIERS = Collections.unmodifiableSet(availableClassifiers); + } + + static boolean addPropertyOsClassifiers(Set<String> allowedClassifiers, Set<String> availableClassifiers) { + // empty: -Dio.netty.osClassifiers (no distro specific classifiers for native libs) + // single ID: -Dio.netty.osClassifiers=ubuntu + // pair ID, ID_LIKE: -Dio.netty.osClassifiers=ubuntu,debian + // illegal otherwise + String osClassifiersPropertyName = "io.netty.osClassifiers"; + String osClassifiers = SystemPropertyUtil.get(osClassifiersPropertyName); + if (osClassifiers == null) { + return false; + } + if (osClassifiers.isEmpty()) { + // let users omit classifiers with just -Dio.netty.osClassifiers + return true; + } + String[] classifiers = osClassifiers.split(","); + if (classifiers.length == 0) { + throw new IllegalArgumentException( + osClassifiersPropertyName + " property is not empty, but contains no classifiers: " + + osClassifiers); + } + // at most ID, ID_LIKE classifiers + if (classifiers.length > 2) { + throw new IllegalArgumentException( + osClassifiersPropertyName + " property contains more than 2 classifiers: " + osClassifiers); + } + for (String classifier : classifiers) { + addClassifier(allowedClassifiers, availableClassifiers, classifier); + } + return true; } public static long byteArrayBaseOffset() {
diff --git a/common/src/test/java/io/netty/util/internal/OsClassifiersTest.java b/common/src/test/java/io/netty/util/internal/OsClassifiersTest.java new file mode 100644 index 00000000000..903f5cba226 --- /dev/null +++ b/common/src/test/java/io/netty/util/internal/OsClassifiersTest.java @@ -0,0 +1,121 @@ +/* + * Copyright 2022 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: + * + * https://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.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Properties; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OsClassifiersTest { + private static final String OS_CLASSIFIERS_PROPERTY = "io.netty.osClassifiers"; + + private Properties systemProperties; + + @BeforeEach + void setUp() { + systemProperties = System.getProperties(); + } + + @AfterEach + void tearDown() { + systemProperties.remove(OS_CLASSIFIERS_PROPERTY); + } + + @Test + void testOsClassifiersPropertyAbsent() { + Set<String> allowed = new HashSet<String>(Arrays.asList("fedora", "suse", "arch")); + Set<String> available = new LinkedHashSet<String>(2); + boolean added = PlatformDependent.addPropertyOsClassifiers(allowed, available); + assertFalse(added); + assertTrue(available.isEmpty()); + } + + @Test + void testOsClassifiersPropertyEmpty() { + // empty property -Dio.netty.osClassifiers + systemProperties.setProperty(OS_CLASSIFIERS_PROPERTY, ""); + Set<String> allowed = Collections.singleton("fedora"); + Set<String> available = new LinkedHashSet<String>(2); + boolean added = PlatformDependent.addPropertyOsClassifiers(allowed, available); + assertTrue(added); + assertTrue(available.isEmpty()); + } + + @Test + void testOsClassifiersPropertyNotEmptyNoClassifiers() { + // ID + systemProperties.setProperty(OS_CLASSIFIERS_PROPERTY, ","); + final Set<String> allowed = new HashSet<String>(Arrays.asList("fedora", "suse", "arch")); + final Set<String> available = new LinkedHashSet<String>(2); + Assertions.assertThrows(IllegalArgumentException.class, new Executable() { + @Override + public void execute() throws Throwable { + PlatformDependent.addPropertyOsClassifiers(allowed, available); + } + }); + } + + @Test + void testOsClassifiersPropertySingle() { + // ID + systemProperties.setProperty(OS_CLASSIFIERS_PROPERTY, "fedora"); + Set<String> allowed = Collections.singleton("fedora"); + Set<String> available = new LinkedHashSet<String>(2); + boolean added = PlatformDependent.addPropertyOsClassifiers(allowed, available); + assertTrue(added); + assertEquals(1, available.size()); + assertEquals("fedora", available.iterator().next()); + } + + @Test + void testOsClassifiersPropertyPair() { + // ID, ID_LIKE + systemProperties.setProperty(OS_CLASSIFIERS_PROPERTY, "manjaro,arch"); + Set<String> allowed = new HashSet<String>(Arrays.asList("fedora", "suse", "arch")); + Set<String> available = new LinkedHashSet<String>(2); + boolean added = PlatformDependent.addPropertyOsClassifiers(allowed, available); + assertTrue(added); + assertEquals(1, available.size()); + assertEquals("arch", available.iterator().next()); + } + + @Test + void testOsClassifiersPropertyExcessive() { + // ID, ID_LIKE, excessive + systemProperties.setProperty(OS_CLASSIFIERS_PROPERTY, "manjaro,arch,slackware"); + final Set<String> allowed = new HashSet<String>(Arrays.asList("fedora", "suse", "arch")); + final Set<String> available = new LinkedHashSet<String>(2); + Assertions.assertThrows(IllegalArgumentException.class, new Executable() { + @Override + public void execute() throws Throwable { + PlatformDependent.addPropertyOsClassifiers(allowed, available); + } + }); + } +}
train
test
"2022-06-15T10:53:31"
"2022-06-16T21:52:24Z"
mostroverkhov
val
netty/netty/12494_12498
netty/netty
netty/netty/12494
netty/netty/12498
[ "connected" ]
c6c3bc606d4e716cf5a08ab68eb950ebb8f989b1
86d4ee41cd917e7b28a691cca1b1d0720e1d5df6
[ "@gspadotto Are you able to make a build with this and give it a try on your system? https://github.com/netty/netty/pull/12498", "> @gspadotto Are you able to make a build with this and give it a try on your system? #12498\r\n\r\nHi @chrisvest \r\nI'll give it a try even though it's a bit complex for me. \r\nI'll explain what the set-up is to reproduce the issue and then I'll ask you some guidance on the \"correct\" way for me to test your patch. \r\n\r\nI have an instance of [this](https://github.com/wso2/micro-integrator/releases/tag/v4.1.0), running inside a [Docker container](https://github.com/wso2/docker-ei/blob/4.1.x/dockerfiles/alpine/micro-integrator/Dockerfile), where [this row](https://github.com/wso2/docker-ei/blob/4.1.x/dockerfiles/alpine/micro-integrator/Dockerfile#L20) has been changed to \"FROM arm64v8/openjdk:11-jdk-slim\".\r\n\r\nThese are the runtime dependencies that refer to Netty: \r\n\r\n```\r\nwso2/components/plugins/io.netty.buffer_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.codec-http2_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.codec-http_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.codec-socks_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.codec_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.common_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.handler-proxy_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.handler_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.resolver_4.1.73.Final.jar\r\nwso2/components/plugins/io.netty.tcnative-boringssl-static_2.0.47.Final.jar\r\nwso2/components/plugins/io.netty.tcnative-classes_2.0.47.Final.jar\r\nwso2/components/plugins/io.netty.tcnative_2.0.47.Final.jar\r\nwso2/components/plugins/io.netty.transport_4.1.73.Final.jar\r\n```\r\n\r\nMy plan for testing is to overwrite only the io.netty.tcnative* jars with the patched ones and see if the OSGi bundles are activated without issues. \r\n\r\nMy questions for you are: \r\n1) Do you think it's ok to \"mix & match\" different versions of netty dependencies?\r\n2) Which components am I supposed to build and embed/overwrite?\r\n3) Can I build netty components for an architecture (arm64) that is different than the one the host that builds the code is running (i.e. \"cross-compiling\")?\r\n\r\nAs a side note, simply editing the manifest file inside the io.netty.tcnative-boringssl-static_2.0.47.Final.jar to read **processor=aarch64** rather than **processor=aarch_64** already fixes the issue: I don't know if this can be considered as a \"successful test\" or not. \r\n\r\nPlease let me know.\r\n" ]
[]
"2022-06-21T23:31:52Z"
[]
Use correct name alias for processor in OSGi Bundle Manifests
https://github.com/netty/netty/blob/f43a9dd0a384eb6226e31648b7168e4fa241527d/transport-native-epoll/pom.xml#L342 **processor** directive value should be "AArch64", not "aarch_64" according to: http://docs.osgi.org/reference/osnames.html See also: https://github.com/netty/netty-tcnative/pull/547 Otherwise you get this error: ``` [2022-06-10 09:50:41,357] ERROR {Framework} - FrameworkEvent ERROR org.osgi.framework.BundleException: Could not resolve module: io.netty.tcnative-boringssl-static [73] Unresolved requirement: Require-Capability: osgi.native; native.paths.0:List<String>="META-INF/native/libnetty_tcnative_osx_x86_64.jnilib"; native.paths.2:List<String>="META-INF/native/libnetty_tcnative_linux_x86_64.so"; native.paths.1:List<String>="META-INF/native/libnetty_tcnative_osx_aarch_64.jnilib"; native.paths.4:List<String>="META-INF/native/netty_tcnative_windows_x86_64.dll"; native.paths.3:List<String>="META-INF/native/libnetty_tcnative_linux_aarch_64.so"; filter:="(|(&(|(osgi.native.osname~=macos)(osgi.native.osname~=macosx))(osgi.native.processor~=x86_64))(&(|(osgi.native.osname~=macos)(osgi.native.osname~=macosx))(osgi.native.processor~=aarch_64))(&(osgi.native.osname~=linux)(osgi.native.processor~=x86_64))(&(osgi.native.osname~=linux)(osgi.native.processor~=aarch_64))(&(osgi.native.osname~=win32)(osgi.native.processor~=x86_64)))" at org.eclipse.osgi.container.Module.start(Module.java:457) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel$1.run(ModuleContainer.java:1820) at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor$2$1.execute(EquinoxContainerAdaptor.java:150) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1813) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.incStartLevel(ModuleContainer.java:1770) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.doContainerStartLevel(ModuleContainer.java:1735) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1661) at org.eclipse.osgi.container.ModuleContainer$ContainerStartLevel.dispatchEvent(ModuleContainer.java:1) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234) at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:345) ``` when running on a container based on the public.ecr.aws/docker/library/openjdk:11-jdk-slim base image for ARM64 architecture.
[ "resolver-dns-native-macos/pom.xml", "transport-native-epoll/pom.xml", "transport-native-kqueue/pom.xml" ]
[ "resolver-dns-native-macos/pom.xml", "transport-native-epoll/pom.xml", "transport-native-kqueue/pom.xml" ]
[]
diff --git a/resolver-dns-native-macos/pom.xml b/resolver-dns-native-macos/pom.xml index 40452e4afba..9c27e028344 100644 --- a/resolver-dns-native-macos/pom.xml +++ b/resolver-dns-native-macos/pom.xml @@ -214,7 +214,7 @@ <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> - <Bundle-NativeCode>META-INF/native/libnetty_resolver_dns_native_macos_aarch_64.jnilib; osname=MacOSX; processor=aarch_64</Bundle-NativeCode> + <Bundle-NativeCode>META-INF/native/libnetty_resolver_dns_native_macos_aarch_64.jnilib; osname=MacOSX; processor=aarch64</Bundle-NativeCode> <Fragment-Host>io.netty.resolver-dns-classes-macos</Fragment-Host> <Automatic-Module-Name>${javaModuleName}</Automatic-Module-Name> </manifestEntries> diff --git a/transport-native-epoll/pom.xml b/transport-native-epoll/pom.xml index 1d3404aae7c..08fe2511130 100644 --- a/transport-native-epoll/pom.xml +++ b/transport-native-epoll/pom.xml @@ -339,7 +339,7 @@ <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> - <Bundle-NativeCode>META-INF/native/libnetty_transport_native_epoll_aarch_64.so; osname=Linux; processor=aarch_64,*</Bundle-NativeCode> + <Bundle-NativeCode>META-INF/native/libnetty_transport_native_epoll_aarch_64.so; osname=Linux; processor=aarch64,*</Bundle-NativeCode> <Fragment-Host>io.netty.transport-classes-epoll</Fragment-Host> <Automatic-Module-Name>${javaModuleName}</Automatic-Module-Name> </manifestEntries> diff --git a/transport-native-kqueue/pom.xml b/transport-native-kqueue/pom.xml index ae16c5d4ad8..0deb193e273 100644 --- a/transport-native-kqueue/pom.xml +++ b/transport-native-kqueue/pom.xml @@ -217,7 +217,7 @@ <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> - <Bundle-NativeCode>META-INF/native/libnetty_transport_native_kqueue_aarch_64.jnilib; osname=MacOSX; processor=aarch_64</Bundle-NativeCode> + <Bundle-NativeCode>META-INF/native/libnetty_transport_native_kqueue_aarch_64.jnilib; osname=MacOSX; processor=aarch64</Bundle-NativeCode> <Fragment-Host>io.netty.transport-classes-kqueue</Fragment-Host> <Automatic-Module-Name>${javaModuleName}</Automatic-Module-Name> </manifestEntries>
null
test
test
"2022-06-21T16:35:38"
"2022-06-21T14:45:42Z"
gspadotto
val
netty/netty/12499_12500
netty/netty
netty/netty/12499
netty/netty/12500
[ "keyword_pr_to_issue" ]
c6c3bc606d4e716cf5a08ab68eb950ebb8f989b1
4e439264df0523fb6efce5f8f6c7c7fa74addd07
[]
[ "actually I think this will not work in netty 4.1 due our java version requirement and so you need to handle this kind of stuff differently.", "The rethrowing Throwable? Then we can use `PlatformDependent.throwException` instead.", "Yep... Only works on java8+" ]
"2022-06-22T21:07:51Z"
[]
ReferenceCountUtil.release(cast) could shade the exception of encode at function write of MessageToMessageEncoder
### Expected behavior ![image](https://user-images.githubusercontent.com/10280338/174937458-9bceea3c-4099-43e7-81c0-0022969f29dc.png) Function `encode` at line 89 is declared to throw exceptions, and then if `ReferenceCountUtil.release(cast)` at line 91 throws an exception too, the exception threw by `encode` will be shown before the exception threw by `ReferenceCountUtil.release(cast)`. ### Actual behavior The excpetion threw by `encode` will be shaded by the exception threw by `ReferenceCountUtil.release(cast)`. ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version on branch 4.1 ### JVM version (e.g. `java -version`) openjdk version "1.8.0_201" ### OS version (e.g. `uname -a`)
[ "codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java b/codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java index eb29eb87fca..4973c9bb0b7 100644 --- a/codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java +++ b/codec/src/main/java/io/netty/handler/codec/MessageToMessageEncoder.java @@ -23,6 +23,7 @@ import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.PromiseCombiner; +import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.TypeParameterMatcher; @@ -87,9 +88,11 @@ public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) I cast = (I) msg; try { encode(ctx, cast, out); - } finally { - ReferenceCountUtil.release(cast); + } catch (Throwable th) { + ReferenceCountUtil.safeRelease(cast); + PlatformDependent.throwException(th); } + ReferenceCountUtil.release(cast); if (out.isEmpty()) { throw new EncoderException(
null
val
test
"2022-06-21T16:35:38"
"2022-06-22T03:47:28Z"
sspbh
val
netty/netty/12360_12662
netty/netty
netty/netty/12360
netty/netty/12662
[ "keyword_pr_to_issue" ]
114762840b2d39018e2254883055c8d34e5846f6
731b7c6240ab1944710982217feca6ddc346e620
[ "A `ByteBuf` was unexpectedly released while being worked on by a `ByteToMessageDecoder`.\r\nWhatever class extends the `ByteToMessageDecoder` probably called `release()` on the `in` buffer argument, which it shouldn't do.\r\nThe input buffer is managed by the `ByteToMessageDecoder`, so sub-classes should just advance the `readerIndex`.", "Hi @chrisvest ,\r\nWe have mix of GET & POST in the traffic. We are performing load testing on our application(1500 TPS. for 42 hours)\r\nThings work fine for 42 hours(All requests are processed). Suddenly the application starts dropping the request with following exception\r\n**[8c5489df, L:/10.233.114.202:8443 - R:/10.233.90.102:56316] EXCEPTION: io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1**\r\nAttaching the stacktrace for reference.\r\nNeed your assistance here to further understand this [behavior]\r\n[StackTrace.txt](https://github.com/netty/netty/files/9242763/StackTrace.txt)\r\n\r\n", "@joyfulnikhil Looks like the same thing. The bug is likely in the `ByteToMessageDecoder` subclass. I've put up a PR to make the error message more helpful." ]
[ "Can a check for **cumulation.refCount() >0** be placed here? This will ensure that only those bytebuf are released whose refCount>0 and if bytebuf already has a refcount of 0, it is already deallocated or can be returned to the object pool. This will prevent IllegalReferenceCount from occurring. \r\nNot sure about the implication on memory (Whether this check will cause a memory leak ?)" ]
"2022-08-02T22:30:49Z"
[]
'io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1'
Hi, We are sending GET requests to our application. We are encountering the issue mentioned below frequently. Dependencies Spring Cloud Gateway - 3.0.3 Spring Boot - 2.5.5 Spring webflux - 5.3.10 Reactor netty - 1.0.11 Netty - 4.1.63.Final OS - Cent OS / Linux ``` {"instant":{"epochSecond":1651180720,"nanoOfSecond":289955175},"thread":"ingress-h2c-epoll-3","level":"WARN","loggerName":"io.netty.channel.DefaultChannelPipeline","message":"An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.","thrown":{"commonElementCount":0,"localizedMessage":"refCnt: 0, decrement: 1","message":"refCnt: 0, decrement: 1","name":"io.netty.util.IllegalReferenceCountException","extendedStackTrace":[{"class":"io.netty.util.internal.ReferenceCountUpdater","method":"toLiveRealRefCnt","file":"ReferenceCountUpdater.java","line":74,"exact":false,"location":"netty-common-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.util.internal.ReferenceCountUpdater","method":"release","file":"ReferenceCountUpdater.java","line":138,"exact":false,"location":"netty-common-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.buffer.AbstractReferenceCountedByteBuf","method":"release","file":"AbstractReferenceCountedByteBuf.java","line":100,"exact":false,"location":"netty-buffer-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.handler.codec.ByteToMessageDecoder","method":"channelRead","file":"ByteToMessageDecoder.java","line":285,"exact":false,"location":"netty-codec-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":379,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":365,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"fireChannelRead","file":"AbstractChannelHandlerContext.java","line":357,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.handler.logging.LoggingHandler","method":"channelRead","file":"LoggingHandler.java","line":271,"exact":true,"location":"netty-handler-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":379,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":365,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"fireChannelRead","file":"AbstractChannelHandlerContext.java","line":357,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.ChannelInboundHandlerAdapter","method":"channelRead","file":"ChannelInboundHandlerAdapter.java","line":93,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"ocpm.cne.gateway.util.ConnectionCountHandler","method":"channelRead","file":"ConnectionCountHandler.java","line":46,"exact":true,"location":"classes!/","version":"?"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":379,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":365,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"fireChannelRead","file":"AbstractChannelHandlerContext.java","line":357,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.DefaultChannelPipeline$HeadContext","method":"channelRead","file":"DefaultChannelPipeline.java","line":1410,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":379,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.AbstractChannelHandlerContext","method":"invokeChannelRead","file":"AbstractChannelHandlerContext.java","line":365,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.DefaultChannelPipeline","method":"fireChannelRead","file":"DefaultChannelPipeline.java","line":919,"exact":true,"location":"netty-transport-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe","method":"epollInReady","file":"AbstractEpollStreamChannel.java","line":795,"exact":true,"location":"netty-transport-native-epoll-4.1.63.Final-linux-x86_64.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.epoll.EpollEventLoop","method":"processReady","file":"EpollEventLoop.java","line":480,"exact":true,"location":"netty-transport-native-epoll-4.1.63.Final-linux-x86_64.jar!/","version":"4.1.63.Final"},{"class":"io.netty.channel.epoll.EpollEventLoop","method":"run","file":"EpollEventLoop.java","line":378,"exact":true,"location":"netty-transport-native-epoll-4.1.63.Final-linux-x86_64.jar!/","version":"4.1.63.Final"},{"class":"io.netty.util.concurrent.SingleThreadEventExecutor$4","method":"run","file":"SingleThreadEventExecutor.java","line":989,"exact":true,"location":"netty-common-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.util.internal.ThreadExecutorMap$2","method":"run","file":"ThreadExecutorMap.java","line":74,"exact":true,"location":"netty-common-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"io.netty.util.concurrent.FastThreadLocalRunnable","method":"run","file":"FastThreadLocalRunnable.java","line":30,"exact":true,"location":"netty-common-4.1.63.Final.jar!/","version":"4.1.63.Final"},{"class":"java.lang.Thread","method":"run","file":"Thread.java","line":833,"exact":true,"location":"?","version":"?"}]},"endOfBatch":false,"loggerFqcn":"io.netty.util.internal.logging.LocationAwareSlf4JLogger","contextMap":{},"threadId":104,"threadPriority":5,"messageTimestamp":"2022-04-28T21:18:40.289+0000","ocLogId":"${ctx:ocLogId}","pod":"${ctx:hostname}","processId":"1","instanceType":"prod","ingressTxId":"${ctx:ingressTxId}"} ``` Please let us know how to resolve this issue?
[ "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java index 39239ec0e3c..81ee3427ce5 100644 --- a/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/ByteToMessageDecoder.java @@ -23,6 +23,7 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.socket.ChannelInputShutdownEvent; +import io.netty.util.IllegalReferenceCountException; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.StringUtil; @@ -285,7 +286,15 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception try { if (cumulation != null && !cumulation.isReadable()) { numReads = 0; - cumulation.release(); + try { + cumulation.release(); + } catch (IllegalReferenceCountException e) { + //noinspection ThrowFromFinallyBlock + throw new IllegalReferenceCountException( + getClass().getSimpleName() + "#decode() might have released its input buffer, " + + "or passed it down the pipeline without a retain() call, " + + "which is not allowed.", e); + } cumulation = null; } else if (++numReads >= discardAfterReads) { // We did enough reads already try to discard some bytes, so we not risk to see a OOME.
null
val
test
"2022-07-29T17:25:27"
"2022-05-05T05:29:24Z"
idikshit
val
netty/netty/12671_12682
netty/netty
netty/netty/12671
netty/netty/12682
[ "keyword_pr_to_issue", "connected" ]
9280cdd49a711192c7290a1043397762bd6f245a
ba129384131dc714496947d8227b1a5a9f7a177c
[ "@chrisvest PTAL", "> Caused by: java.lang.IllegalStateException: This allocator has been **closed**.\r\n> \tat io.netty5.buffer.api.internal.Statics.allocatorClosedException(Statics.java:268)\r\n> \tat io.netty5.buffer.api.pool.PooledBufferAllocator.allocate(PooledBufferAllocator.java:316)\r\n> \tat io.netty5.buffer.api.DefaultBufferAllocators$**UncloseableBufferAllocator**.allocate(DefaultBufferAllocators.java:129)\r\n\r\nQuite the mystery, here… 🤔 \r\n\r\nI'll take a look." ]
[]
"2022-08-08T21:55:31Z"
[]
[netty 5] ByteToMessageDecoder tries to allocate from a closed allocator
### Expected behavior ByteToMessageDecoder shouldn't try to allocate a buffer from a closed allocator. ### Actual behavior ByteToMessageDecoder tries to call decode when a channel becomes inactive which tries to allocate a buffer from a closed buffer allocator: https://gist.github.com/derklaro/38899e5d645adc058785e2197da0cdc6 Not sure if I am using something wrong (wrong call order?)... This seems to only sometimes happen during shutdown 🤔 ### Netty version 5.0.0.Alpha4 ### JVM version (e.g. `java -version`) ``` openjdk version "20-ea" 2023-03-21 OpenJDK Runtime Environment (build 20-ea+9-505) OpenJDK 64-Bit Server VM (build 20-ea+9-505, mixed mode, sharing) ``` ### OS version (e.g. `uname -a`) `Linux testing 5.10.0-16-amd64 #1 SMP Debian 5.10.127-1 (2022-06-30) x86_64 GNU/Linux`
[ "buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java" ]
[ "buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java" ]
[]
diff --git a/buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java b/buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java index 10329926727..44b7a4fa611 100644 --- a/buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java +++ b/buffer/src/main/java/io/netty5/buffer/api/DefaultBufferAllocators.java @@ -61,12 +61,6 @@ public final class DefaultBufferAllocators { offHeap = BufferAllocator.offHeapPooled(); logger.debug("-Dio.netty5.allocator.type: pooled (unknown: {})", allocType); } - getRuntime().addShutdownHook(new Thread(() -> { - //noinspection EmptyTryBlock - try (onHeap; offHeap) { - // Left blank. - } - })); UncloseableBufferAllocator onHeapUnclosable = new UncloseableBufferAllocator(onHeap); UncloseableBufferAllocator offHeapUnclosable = new UncloseableBufferAllocator(offHeap); DEFAULT_PREFERRED_ALLOCATOR = directBufferPreferred? offHeapUnclosable : onHeapUnclosable;
null
val
test
"2022-08-08T22:32:31"
"2022-08-06T17:58:23Z"
derklaro
val
netty/netty/11020_12732
netty/netty
netty/netty/11020
netty/netty/12732
[ "keyword_pr_to_issue" ]
57dbfb0aeb734164435d2b08e733ba52717e222c
8957a2e36a0d0f794af7556e838dbbf194f58ad0
[ "Never saw this big stack trace. ;/", "make sure you have:\r\n\r\n```\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>XXX</version>\r\n <classifier>osx-x86_64</classifier>\r\n </dependency>\r\n```\r\n\r\nin your class path on OS X", "faced with the same problem in Redisson yesterday,\r\nthanx @vietj, your answer was so in time", "> make sure you have:\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n> <version>XXX</version>\r\n> <classifier>osx-x86_64</classifier>\r\n> </dependency>\r\n> ```\r\n> \r\n> in your class path on OS X\r\n\r\nDoesn't fix the issue anymore.", "For Gradle (with Kotlin syntax) it is:\r\n```\r\nruntimeOnly(\"io.netty:netty-resolver-dns-native-macos:XXX:osx-x86_64\")\r\n```\r\n\r\nWhere `XXX` is version of [netty-resolver-dns-native-macos](https://mvnrepository.com/artifact/io.netty/netty-resolver-dns-native-macos)", "I still get this issue on an Apple M1. I guess there needs to be a DnsServer provider that supports the M1?", "@philsmart we currently not support M1.", "OK, thanks for the update.", "@normanmaurer do you have any workaround or any idea when M1 will be supported?", "@normanmaurer still no update 3 months later ?", "Sorry missed this one. We added supported in the last release (4.1.68.Final).", "> Sorry missed this one. We added supported in the last release (4.1.68.Final).\r\n\r\nI still have the same issue.\r\n\r\n`2021-09-19 12:11:56.115 ERROR 4560 --- [undedElastic-11] i.n.r.d.DnsServerAddressStreamProviders : Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider, fallback to system defaults. This may result in incorrect DNS resolutions on MacOS.\r\n\r\njava.lang.reflect.InvocationTargetException: null\r\n\tat java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]\r\n\tat java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78) ~[na:na]\r\n\tat java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]\r\n\tat java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]\r\n\tat java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]\r\n\tat io.netty.resolver.dns.DnsServerAddressStreamProviders.<clinit>(DnsServerAddressStreamProviders.java:64) ~[netty-resolver-dns-4.1.68.Final.jar:4.1.68.Final]\r\n\tat io.netty.resolver.dns.DnsNameResolverBuilder.<init>(DnsNameResolverBuilder.java:60) ~[netty-resolver-dns-4.1.68.Final.jar:4.1.68.Final]\r\n\tat reactor.netty.transport.NameResolverProvider.newNameResolverGroup(NameResolverProvider.java:432) ~[reactor-netty-core-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.tcp.TcpResources.getOrCreateDefaultResolver(TcpResources.java:305) ~[reactor-netty-core-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.http.HttpResources.getOrCreateDefaultResolver(HttpResources.java:139) ~[reactor-netty-http-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.http.client.HttpClientConfig.defaultAddressResolverGroup(HttpClientConfig.java:382) ~[reactor-netty-http-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.transport.ClientTransportConfig.resolverInternal(ClientTransportConfig.java:223) ~[reactor-netty-core-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.http.client.HttpClientConfig.resolverInternal(HttpClientConfig.java:436) ~[reactor-netty-http-1.0.11.jar:1.0.11]\r\n\tat reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.lambda$subscribe$0(HttpClientConnect.java:264) ~[reactor-netty-http-1.0.11.jar:1.0.11]\r\n\tat reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:57) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxRetryWhen.subscribe(FluxRetryWhen.java:77) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoRetryWhen.subscribeOrReturn(MonoRetryWhen.java:46) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.subscribe(HttpClientConnect.java:271) ~[reactor-netty-http-1.0.11.jar:1.0.11]\r\n\tat reactor.core.publisher.Flux.subscribe(Flux.java:8468) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:255) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:236) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:203) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.onComplete(FluxPeek.java:260) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:142) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:102) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:83) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:98) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:44) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.drainAsync(FluxFlattenIterable.java:421) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.drain(FluxFlattenIterable.java:686) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxFlattenIterable$FlattenIterableSubscriber.onNext(FluxFlattenIterable.java:250) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:74) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1816) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:249) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.complete(MonoIgnoreThen.java:284) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onNext(MonoIgnoreThen.java:187) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:232) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.onComplete(MonoIgnoreThen.java:203) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreElements$IgnoreElementsSubscriber.onComplete(MonoIgnoreElements.java:89) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.onComplete(FluxPeek.java:260) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onComplete(FluxDematerialize.java:121) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:91) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:44) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable$IterableSubscription.fastPath(FluxIterable.java:340) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:227) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.request(FluxDematerialize.java:127) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.request(FluxPeek.java:138) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreElements$IgnoreElementsSubscriber.onSubscribe(MonoIgnoreElements.java:72) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxPeek$PeekSubscriber.onSubscribe(FluxPeek.java:171) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onSubscribe(FluxDematerialize.java:77) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Mono.subscribe(Mono.java:4361) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.subscribeNext(MonoIgnoreThen.java:255) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:51) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1816) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onComplete(MonoCollectList.java:128) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.DrainUtils.postCompleteDrain(DrainUtils.java:132) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.DrainUtils.postComplete(DrainUtils.java:187) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxMaterialize$MaterializeSubscriber.onComplete(FluxMaterialize.java:141) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxTake$TakeSubscriber.onComplete(FluxTake.java:153) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxTake$TakeSubscriber.onNext(FluxTake.java:133) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.SerializedSubscriber.onNext(SerializedSubscriber.java:99) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxTimeout$TimeoutMainSubscriber.onNext(FluxTimeout.java:180) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1816) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.MonoCollectList$MonoCollectListSubscriber.onComplete(MonoCollectList.java:128) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat org.springframework.cloud.commons.publisher.FluxFirstNonEmptyEmitting$FirstNonEmptyEmittingSubscriber.onComplete(FluxFirstNonEmptyEmitting.java:325) ~[spring-cloud-commons-3.1.0-SNAPSHOT.jar:3.1.0-SNAPSHOT]\r\n\tat reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.onComplete(FluxSubscribeOn.java:166) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:2058) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable$IterableSubscription.fastPath(FluxIterable.java:362) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:227) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.Operators$MultiSubscriptionSubscriber.set(Operators.java:2194) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onSubscribe(FluxOnErrorResume.java:74) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:54) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.publisher.FluxSubscribeOn$SubscribeOnSubscriber.run(FluxSubscribeOn.java:194) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.scheduler.WorkerTask.call(WorkerTask.java:84) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat reactor.core.scheduler.WorkerTask.call(WorkerTask.java:37) ~[reactor-core-3.4.10.jar:3.4.10]\r\n\tat java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]\r\n\tat java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]\r\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]\r\n\tat java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]\r\nCaused by: java.lang.UnsatisfiedLinkError: 'io.netty.resolver.dns.macos.DnsResolver[] io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.resolvers()'\r\n\tat io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.resolvers(Native Method) ~[netty-resolver-dns-native-macos-4.1.68.Final.jar:4.1.68.Final]\r\n\tat io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.retrieveCurrentMappings(MacOSDnsServerAddressStreamProvider.java:127) ~[netty-resolver-dns-native-macos-4.1.68.Final.jar:4.1.68.Final]\r\n\tat io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.<init>(MacOSDnsServerAddressStreamProvider.java:123) ~[netty-resolver-dns-native-macos-4.1.68.Final.jar:4.1.68.Final]\r\n\t... 91 common frames omitted\r\n\r\n`", "> @normanmaurer do you have any workaround or any idea when M1 will be supported?\r\n\r\nI use implementation(group = \"io.netty\",name = \"netty-resolver-dns-native-macos\", version = \"4.1.70.Final\", classifier = \"osx-aarch_64\")", "Same problem with M1 macbook. Tried this but didn't help: \r\n\r\n```\r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.72.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n</dependency>\r\n```", "> Same problem with M1 macbook. Tried this but didn't help:\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n> <version>4.1.72.Final</version>\r\n> <classifier>osx-aarch_64</classifier>\r\n> </dependency>\r\n> ```\r\n\r\nworks fine for me on spring boot 2.5.3", "You could also use the following code to fix an error\r\n\r\n```\r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-all</artifactId>\r\n</dependency>\r\n```\r\n\r\nhttps://stackoverflow.com/a/65976398/3001953", "I have this problem on M1 MacOS with latest Spring Boot", "I have this problem on M1 MacOS with Spring boot 2.5.5", "use below dependency for M1 based mac, it works for me.\r\nimplementation 'io.netty:netty-resolver-dns-native-macos:4.1.72.Final:osx-aarch_64'\r\n", "> use below dependency for M1 based mac, it works for me.\r\n> implementation 'io.netty:netty-resolver-dns-native-macos:4.1.72.Final:osx-aarch_64'\r\n\r\nI test on M1 Mac and deploy to a Docker image that runs on x86. Sorry for my stupid question: How can I include above dependency during development and exclude it from my production Docker image?", "@ksilz there is no need to exclude as it will just not use it on linux if you use linux. If you run on Mac x86 on prod you will need to use the correct classifier when deploying. ", "Adding this resolved my issue with M1. This <classifier>osx-x86_64</classifier> did not work until i switched to below.\r\n```\r\n\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.73.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n```", "> use below dependency for M1 based mac, it works for me. implementation 'io.netty:netty-resolver-dns-native-macos:4.1.72.Final:osx-aarch_64'\r\n\r\nIt works for me\r\n\r\n\r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.73.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n</dependency>", "io.netty netty-resolver-dns-native-macos 4.1.73.Final osx-aarch_64 doesnt work on my M1 pro machine with Spring Boot 2.6.1. Are there any updates planned? \r\n\r\n**Update:** io.netty:netty-all:4.1.73.Final works on my M1 pro with Spring Boot 2.6.1", "I'm using OSX on Intel and I'm having the same problem when I try to run Spring Boot above 2.6.1. Spring Boot 2.6.1 works though. Adding the above mentioned package did not solve the issue for me.", "M1 mac os:\r\n1. exclude netty-resolver-dns-native-macos\r\n2. add classifier of osx-aarch_64.\r\n `<dependency>\r\n <groupId>io.projectreactor.netty</groupId>\r\n <artifactId>reactor-netty-core</artifactId>\r\n <exclusions>\r\n <exclusion>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n </exclusion>\r\n </exclusions>\r\n </dependency>\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.72.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>`", "I am using on a MacBook Pro (x86_64) with Spring Boot 2.5.9, and spring-boot-starter-webflux 2.5.9 already pull in the native macos jar, but my running system cannot load it. I tried excluding the one from webflux and adding it directly, but it still doesn't work. Are there any other suggestions?", "To ensure a more timely response, please reply to this email with your POM file.I will resolve this question for you soon.发自我的iPhone------------------ Original ------------------From: Bryan Pugh ***@***.***>Date: Fri, Feb 18, 2022 8:26 AMTo: netty/netty ***@***.***>Cc: wanglianglike ***@***.***>, Comment ***@***.***>Subject: Re: [netty/netty] Unable to loadio.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider (#11020)\nI am using on a MacBook Pro (x86_64) with Spring Book 2.5.9, and spring-boot-starter-webflux 2.5.9 already pull in the native macos jar, but my running system cannot load it. I tried excluding the one from webflux and adding it directly, but it still doesn't work. Are there any other suggestions?\n\n—Reply to this email directly, view it on GitHub, or unsubscribe.Triage notifications on the go with GitHub Mobile for iOS or Android.\nYou are receiving this because you commented.Message ID: ***@***.***>\n[\n{\n***@***.***\": \"http://schema.org\",\n***@***.***\": \"EmailMessage\",\n\"potentialAction\": {\n***@***.***\": \"ViewAction\",\n\"target\": \"https://github.com/netty/netty/issues/11020#issuecomment-1043672377\",\n\"url\": \"https://github.com/netty/netty/issues/11020#issuecomment-1043672377\",\n\"name\": \"View Issue\"\n},\n\"description\": \"View this Issue on GitHub\",\n\"publisher\": {\n***@***.***\": \"Organization\",\n\"name\": \"GitHub\",\n\"url\": \"https://github.com\"\n}\n}\n]", "I fixed the problem by upgrading from JDK 11.0.4 to 11.0.11.", "> I fixed the problem by upgrading from JDK 11.0.4 to 11.0.11.\r\n\r\nI can reproduce this problem on openjdk 17.0.2.", "> > I fixed the problem by upgrading from JDK 11.0.4 to 11.0.11.\r\n> \r\n> I can reproduce this problem on openjdk 17.0.2.\r\n\r\nI am using openjdk version \"17.0.2\", spring boot '3.0.0-SNAPSHOT' and still getting this exception on M1. Also tried with above fix but not working for me.", "> \r\n\r\nthis work for me, thank you", "> You could also use the following code to fix an error\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-all</artifactId>\r\n> </dependency>\r\n> ```\r\n> \r\n> https://stackoverflow.com/a/65976398/3001953\r\nThis fixed the issue on my MacBook Pro M1\r\n", "> Same problem with M1 macbook. Tried this but didn't help:\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n> <version>4.1.72.Final</version>\r\n> <classifier>osx-aarch_64</classifier>\r\n> </dependency>\r\n> ```\r\n\r\nthis worked for me", "The dependency has only runtime scope:\r\n\r\n`runtimeOnly \"io.netty:netty-resolver-dns-native-macos:4.1.76.Final:osx-aarch_64\"`\r\n\r\nHow can we make this dependency platform agnostic?\r\nWe don't really want to have a platform dependency in our java builds.", "I added `runtimeOnly(\"io.netty:netty-resolver-dns-native-macos:4.1.77.Final:osx-aarch_64\")` to my dependencies and still facing the issue. I played a little bit around with different versions of both netty and SpringBoot but nothing helps so far. I have an M1 chip on a MB Pro 2020. Any ideas on that?", "I have this problem on M1 MacOS with Spring boot 2.6.7", "Even when adding the correct version maven or gradle in the end might resolve to another version.\r\nTo validate the version you need to look into the resulting dependency tree.\r\n\r\n```\r\nmvn dependency:tree\r\ngradle dependencies\r\n```\r\n", "> I have this problem on M1 MacOS with Spring boot 2.6.7\r\n\r\nSame issue with spring boot 2.7.0 too", "I got it to work on my M1 Pro but none of the solutions above worked for me. The switch to Spring Boot 2.6.7 triggered the DNS resolver issue. I've had to override the dependency with the version below to get it to work locally (Spring Boot 2.6.7 provides 1.0.18):\r\n` <dependency>\r\n <groupId>io.projectreactor.netty</groupId>\r\n <artifactId>reactor-netty</artifactId>\r\n <version>0.9.20.RELEASE</version>\r\n </dependency>`\r\n\r\nGoing for an older version doesn't seem ideal though...", "workaround\r\n\r\n```kotlin\r\n// build.gradle.ktx\r\n\r\ndependencies {\r\n \r\n // ...\r\n\r\n // mac silicon only\r\n // https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/SystemUtils.java#L1173\r\n val isMacOS: Boolean = System.getProperty(\"os.name\").startsWith(\"Mac OS X\")\r\n val architecture = System.getProperty(\"os.arch\").toLowerCase()\r\n if (isMacOS && architecture == \"aarch64\") {\r\n developmentOnly(\"io.netty:netty-resolver-dns-native-macos:4.1.68.Final:osx-aarch_64\")\r\n }\r\n\r\n // ...\r\n\r\n}\r\n```", "this works for me\r\n`implementation 'io.netty:netty-all'`\r\n`implementation(group: \"io.netty\", name: \"netty-resolver-dns-native-macos\", version: \"4.1.72.Final\", classifier: \"osx-aarch_64\")`", "It looks like this is an issue in [io.projectreactor.netty:reactor-netty-http:1.0.22](https://search.maven.org/artifact/io.projectreactor.netty/reactor-netty-http/1.0.22/jar), because that has a hardcoded dependency on `io.netty:netty-resolver-dns-native-macos` with classifier `osx-x86_64`.", "For Maven the workaround looks like following:\r\n`\r\n<dependency>\r\n <groupId>org.springframework.boot</groupId>\r\n <artifactId>spring-boot-starter-webflux</artifactId>\r\n <exclusions>\r\n <exclusion>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n </exclusion>\r\n </exclusions>\r\n </dependency>\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.73.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n`\r\nFirst exclude the referenced library. And then add it explicit with the classifier. Worked on M2 chip MacBook Pro 2022.", "If you don't want to include native support properly (arm & intel) you should scope the dependency not as \"implementation\" but rather as \"compileOnly\" - (talking gradle slang :-) and document which dependencies can be included optionally.", "In Gradle, you can use [osdetector-gradle-plugin](https://github.com/google/osdetector-gradle-plugin) to fetch dependencies for specific platforms:\r\n\r\n```kotlin\r\n// build.gradle.kts\r\n\r\nplugins {\r\n id(\"com.google.osdetector\") version \"1.7.1\"\r\n}\r\n\r\ndependencies {\r\n if (osdetector.classifier == \"osx-aarch_64\") {\r\n runtimeOnly(\"io.netty:netty-resolver-dns-native-macos:4.1.77.Final:${osdetector.classifier}\")\r\n }\r\n}\r\n```", "> I still get this issue on an Apple M1. I guess there needs to be a DnsServer provider that supports the M1?\r\nme too M1 , i use this pom solve this problem. \r\n\r\nartifactId like this \r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-all</artifactId>\r\n <version>4.1.84.Final</version>\r\n </dependency>", "> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <exclusions> <exclusion> <groupId>io.netty</groupId> <artifactId>netty-resolver-dns-native-macos</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-resolver-dns-native-macos</artifactId> <version>4.1.73.Final</version> <classifier>osx-aarch_64</classifier> </dependency>\r\n\r\nThis has worked for me - M1 Pro 2022", "> In Gradle, you can use [osdetector-gradle-plugin](https://github.com/google/osdetector-gradle-plugin) to fetch dependencies for specific platforms:\r\n> \r\n> ```kotlin\r\n> // build.gradle.kts\r\n> \r\n> plugins {\r\n> id(\"com.google.osdetector\") version \"1.7.1\"\r\n> }\r\n> \r\n> dependencies {\r\n> if (osdetector.classifier == \"osx-aarch_64\") {\r\n> runtimeOnly(\"io.netty:netty-resolver-dns-native-macos:4.1.77.Final:${osdetector.classifier}\")\r\n> }\r\n> }\r\n> ```\r\n\r\nNote that if you deploy on a different OS/arch than the one you build on, this doesn't really solve the issue. This resolver is a runtime component, so the OS/arch of the build machine is not necessarily the same.\r\n\r\nHowever, I don't believe it's a problem to just include resolvers for multiple architectures in your application. The one to use will be resolved at runtime.", "**PROBLEM with null**\r\n\r\nWe have issues with Webflux and get null as a response (both in the console in our react native project and in Postman). \r\n\r\nWe have macos M1 and run the application with Spring boot version 3.0.0. We have added below mentioned dependency and it removed the bug with failed build. \r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.86.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n</dependency>\r\n\r\nWe have used Webflux before and it worked like a charm with above mentioned dependency, but that project was run with Spring boot version 2.7.5. \r\n\r\nI have no idea if this matters at all, but I should also mention that we use Jakarta to serialize our entity objects. \r\n\r\nOur friend that uses PC has no problems with the serialization.\r\n\r\nAny ideas on what we might have done wrong? We get no error messages so, unfortunately, there is nothing to show.\r\nThanks in advance for any suggestions on how to move forward!", "I have this error today without knowing why, I tried every step here and nothing worked.", "I had trouble with an API key to google, which was an underlying problem. And when that was fixed, I used this and made it work: \r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <version>4.1.76.Final</version>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n\r\nHope it works out for you AlexLombry!", "For maven and a project where this is only needed for local development on machines running mac M1 you can use a profile activated based on the OS:\r\n```\r\n <profile>\r\n <id>macos-m1</id>\r\n <activation>\r\n <os>\r\n <family>mac</family>\r\n <arch>aarch64</arch>\r\n </os>\r\n </activation>\r\n <dependencies>\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n </dependencies>\r\n </profile>\r\n```", "mac M1 with build.gradle.kts\r\n\r\n```kts\r\n testImplementation(\r\n group = \"io.netty\",\r\n name = \"netty-resolver-dns-native-macos\",\r\n classifier = \"osx-aarch_64\"\r\n )\r\n```", "> mac M1 with build.gradle.kts\r\n> \r\n> ```kotlin\r\n> testImplementation(\r\n> group = \"io.netty\",\r\n> name = \"netty-resolver-dns-native-macos\",\r\n> classifier = \"osx-aarch_64\"\r\n> )\r\n> ```\r\n\r\nThanks! This worked for me. I also locked mine to Mac M1 machines only since we use different kinds of machines here at work:\r\n```groovy\r\n\tdef isMacOS = System.getProperty('os.name').startsWith('Mac OS X')\r\n\tdef architecture = System.getProperty('os.arch').toLowerCase()\r\n\tif (isMacOS && architecture == 'aarch64') {\r\n\t\ttestImplementation('io.netty:netty-resolver-dns-native-macos:4.1.90.Final:osx-aarch_64')\r\n\t}\r\n```", "> For maven and a project where this is only needed for local development on machines running mac M1 you can use a profile activated based on the OS:\r\n> \r\n> ```\r\n> <profile>\r\n> <id>macos-m1</id>\r\n> <activation>\r\n> <os>\r\n> <family>mac</family>\r\n> <arch>aarch64</arch>\r\n> </os>\r\n> </activation>\r\n> <dependencies>\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n> <classifier>osx-aarch_64</classifier>\r\n> </dependency>\r\n> </dependencies>\r\n> </profile>\r\n> ```\r\n\r\n~~FYI: Maven doesn't allow to declare dependencies in this place. Unfortunately the single solution is to declare this dependency with classifier `osx-aarch_64` per project or in some parent POM.~~\n\nWrong, see below.", "According to https://maven.apache.org/guides/introduction/introduction-to-profiles.html#Profiles_in_POMs Maven profiles can modify `<dependencies>`.", "> According to https://maven.apache.org/guides/introduction/introduction-to-profiles.html#Profiles_in_POMs Maven profiles can modify `<dependencies>`.\n\nHmmm, you're right. Seems that it works **only** when used in some of the project's POMs, but doesn't work outside the project e.g. in the user's `settings.xml` 🤔", "Yeah, this method worked for me when used in the project's POM.", "Fellows,\r\n\r\nI've stumbled upon this in my project recently. My two cents: while I do develop things on my M1 Mac, and this is an annoying issue, I never intend to run a production environment on my laptop 😂. With that been said, how do I make sure that the problem won't bite me when I deploy my code to a cloud provider? \r\n\r\nAny reflection on the 👆🏻 is greatly appreciated! \r\n\r\n\r\n ", "@singulart As far as I can see the code will only be loaded on an ARM Mac and it's also a pretty small library, so it should be harmless to add the dependency by default. Or, assuming your CI hardware is not ARM Mac, you can add the dependency only when building on ARM Macs using an auto-activating Maven profile like this:\r\n\r\n```\r\n<profile>\r\n <id>netty-resolver-dns-native-macos-aarch64</id>\r\n <activation>\r\n <os>\r\n <family>mac</family>\r\n <arch>aarch64</arch>\r\n </os>\r\n </activation>\r\n <dependencies>\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n </dependencies>\r\n</profile>\r\n```", " implementation('io.netty:netty-resolver-dns-native-macos')\r\nThis worked for me today", "> io.netty netty-resolver-dns-native-macos 4.1.73.Final osx-aarch_64 doesnt work on my M1 pro machine with Spring Boot 2.6.1. Are there any updates planned?\r\n> \r\n> **Update:** io.netty:netty-all:4.1.73.Final works on my M1 pro with Spring Boot 2.6.1\r\n\r\nThis worked for me... thanks!", "\r\n ERROR 2481 --- [API-GATEWAY] [ender@6e0b642c}] [ ] i.n.r.d.DnsServerAddressStreamProviders : Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider, fallback to system defaults. This may result in incorrect DNS resolutions on MacOS. Check whether you have a dependency on 'io.netty:netty-resolver-dns-native-macos'. Use DEBUG level to see the full stack: java.lang.UnsatisfiedLinkError: failed to load the required native library \r\n\r\nGetting the above error when i am using Spring Reactive Web dependancy on my spring boot microservice to create API-GATEWAY. I am using it on Macbook air M1 laptop. tried adding the following dependancy and other possible solutions like creating profile but it is not fixing my issue. \r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <classifier>osx-aarch_64</classifier>\r\n</dependency> \r\n\r\nPlease suggest me , how i can resolve this issue. ", "# following setup works. \r\n\r\nApple M1/Sonama 14.4.1 \r\nJava : 17-Temurin \r\nSpring Boot: 3.2.4 \r\nAzure, Postgresql \r\n\r\nworks fine. latest versions are not working. fyi. \r\n\r\n```xml\r\n <dependency>\r\n <groupId>io.projectreactor.netty</groupId>\r\n <artifactId>reactor-netty-http</artifactId>\r\n <version>1.0.39</version>\r\n </dependency>\r\n <dependency>\r\n <groupId>io.projectreactor.netty</groupId>\r\n <artifactId>reactor-netty-core</artifactId>\r\n <version>1.0.39</version>\r\n </dependency>\r\n <dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <classifier>osx-aarch_64</classifier>\r\n </dependency>\r\n```", "~~Mac M3 this is work for me~~\r\n\r\n```\r\n<dependency>\r\n <groupId>io.netty</groupId>\r\n <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n <classifier>${os.detected.classifier}</classifier>\r\n </dependency>\r\n\r\n<build>\r\n <extensions>\r\n <extension>\r\n <groupId>kr.motd.maven</groupId>\r\n <artifactId>os-maven-plugin</artifactId>\r\n <version>1.7.1</version>\r\n </extension>\r\n </extensions>\r\n </build>\r\n```\r\n\r\n:cry: It look like os.detected.classifier can not used in dependency tag.... \r\n\r\ntry https://github.com/netty/netty/issues/11020#issuecomment-1570501849\r\n\r\n", "> Mac M3 this is work for me\r\n> \r\n> ```\r\n> <dependency>\r\n> <groupId>io.netty</groupId>\r\n> <artifactId>netty-resolver-dns-native-macos</artifactId>\r\n> <classifier>${os.detected.classifier}</classifier>\r\n> </dependency>\r\n> </dependencies>\r\n> \r\n> <build>\r\n> <extensions>\r\n> <extension>\r\n> <groupId>kr.motd.maven</groupId>\r\n> <artifactId>os-maven-plugin</artifactId>\r\n> <version>1.7.1</version>\r\n> </extension>\r\n> </extensions>\r\n> </build>\r\n> ```\r\n\r\n@shalk You're making the `classifier` dynamic based on OS but `artifactId` contains a static `macos` part 😬 \r\n\r\nMoreover you're adding an additional Maven extension which currently has \"just\" 293 starts...\r\n\r\n@breun 's solution with a Maven profile and `activation` block is more robust and thought out, at least in my opinion.", "> Moreover you're adding an additional Maven plugin which currently has \"just\" 293 starts...\r\n\r\nThe extension is maintained by @trustin, and we use it in Netty." ]
[ "```suggestion\r\n + \"incorrect DNS resolutions on MacOS. Check whether you have a dependency on \"\r\n```", "```suggestion\r\n + \"incorrect DNS resolutions on MacOS. Check whether you have a dependency on \"\r\n```", "thanks", "thanks" ]
"2022-08-24T07:47:12Z"
[]
Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider
### Expected behavior Spring Cloud Gateway microservice (api-gateway) should route to appropriate microservice (web) using Eureka Discovery Server microservice (discovery) and return "Hello World". ### Actual behavior ``` 2021-02-12 15:31:29.621 INFO 8598 --- [ main] com.example.demo.ApiGatewayApplication : Started ApiGatewayApplication in 3.165 seconds (JVM running for 3.989) Available Services: web 2021-02-12 15:31:49.069 WARN 8598 --- [ctor-http-nio-2] i.n.r.d.DnsServerAddressStreamProviders : Unable to load io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider, fallback to system defaults. This may result in incorrect DNS resolutions on MacOS. java.lang.reflect.InvocationTargetException: null at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64) ~[na:na] at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481) ~[na:na] at io.netty.resolver.dns.DnsServerAddressStreamProviders.<clinit>(DnsServerAddressStreamProviders.java:64) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsNameResolverBuilder.<init>(DnsNameResolverBuilder.java:58) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at reactor.netty.transport.NameResolverProvider.newNameResolverGroup(NameResolverProvider.java:405) ~[reactor-netty-core-1.0.3.jar:1.0.3] at reactor.netty.transport.ClientTransportConfig.getOrCreateDefaultResolver(ClientTransportConfig.java:230) ~[reactor-netty-core-1.0.3.jar:1.0.3] at reactor.netty.transport.ClientTransportConfig.resolverInternal(ClientTransportConfig.java:216) ~[reactor-netty-core-1.0.3.jar:1.0.3] at reactor.netty.http.client.HttpClientConfig.resolverInternal(HttpClientConfig.java:420) ~[reactor-netty-http-1.0.3.jar:1.0.3] at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.lambda$subscribe$0(HttpClientConnect.java:262) ~[reactor-netty-http-1.0.3.jar:1.0.3] at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect$$Lambda$880/0x0000000058616148.accept(Unknown Source) ~[na:na] at reactor.core.publisher.MonoCreate.subscribe(MonoCreate.java:57) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxRetryWhen.subscribe(FluxRetryWhen.java:76) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoRetryWhen.subscribeOrReturn(MonoRetryWhen.java:46) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:57) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.netty.http.client.HttpClientConnect$MonoHttpConnect.subscribe(HttpClientConnect.java:269) ~[reactor-netty-http-1.0.3.jar:1.0.3] at reactor.core.publisher.Flux.subscribe(Flux.java:8147) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:173) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:154) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Mono.subscribe(Mono.java:4046) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:173) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Mono.subscribe(Mono.java:4046) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:173) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:157) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:73) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:281) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:860) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:120) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FluxSwitchIfEmpty.java:73) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1789) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:151) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:120) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:82) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:281) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:860) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:79) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onNext(MonoPeekTerminal.java:180) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1789) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoFilterWhen$MonoFilterWhenMain.onNext(MonoFilterWhen.java:149) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Operators$ScalarSubscription.request(Operators.java:2359) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoFilterWhen$MonoFilterWhenMain.onSubscribe(MonoFilterWhen.java:112) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoJust.subscribe(MonoJust.java:54) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Mono.subscribe(Mono.java:4046) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:448) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onNext(FluxConcatMap.java:250) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:98) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onNext(FluxDematerialize.java:44) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:270) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:228) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.request(FluxDematerialize.java:127) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:235) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxDematerialize$DematerializeSubscriber.onSubscribe(FluxDematerialize.java:77) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:164) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:86) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:54) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Mono.subscribe(Mono.java:4046) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.drain(FluxConcatMap.java:448) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.onSubscribe(FluxConcatMap.java:218) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:164) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:86) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.Mono.subscribe(Mono.java:4046) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain.drain(MonoIgnoreThen.java:173) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.MonoIgnoreThen.subscribe(MonoIgnoreThen.java:56) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.core.publisher.InternalMonoOperator.subscribe(InternalMonoOperator.java:64) ~[reactor-core-3.4.2.jar:3.4.2] at reactor.netty.http.server.HttpServer$HttpServerHandle.onStateChange(HttpServer.java:860) ~[reactor-netty-http-1.0.3.jar:1.0.3] at reactor.netty.ReactorNetty$CompositeConnectionObserver.onStateChange(ReactorNetty.java:638) ~[reactor-netty-core-1.0.3.jar:1.0.3] at reactor.netty.transport.ServerTransport$ChildObserver.onStateChange(ServerTransport.java:475) ~[reactor-netty-core-1.0.3.jar:1.0.3] at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:525) ~[reactor-netty-http-1.0.3.jar:1.0.3] at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:94) ~[reactor-netty-core-1.0.3.jar:1.0.3] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:209) ~[reactor-netty-http-1.0.3.jar:1.0.3] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324) ~[netty-codec-4.1.58.Final.jar:4.1.58.Final] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296) ~[netty-codec-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at java.base/java.lang.Thread.run(Thread.java:845) ~[na:na] Caused by: java.lang.UnsatisfiedLinkError: io/netty/resolver/dns/macos/MacOSDnsServerAddressStreamProvider.resolvers()[Lio/netty/resolver/dns/macos/DnsResolver; at io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.retrieveCurrentMappings(MacOSDnsServerAddressStreamProvider.java:107) ~[netty-resolver-dns-native-macos-4.1.58.Final-osx-x86_64.jar:4.1.58.Final] at io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider.<init>(MacOSDnsServerAddressStreamProvider.java:103) ~[netty-resolver-dns-native-macos-4.1.58.Final-osx-x86_64.jar:4.1.58.Final] ... 119 common frames omitted 2021-02-12 15:31:54.213 ERROR 8598 --- [ctor-http-nio-4] a.w.r.e.AbstractErrorWebExceptionHandler : [884707ab-1] 500 Server Error for HTTP GET "/api/v1/test" java.net.UnknownHostException: failed to resolve '192-168-1-107.tpgi.com.au' after 2 queries at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: Error has been observed at the following site(s): |_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain] |_ checkpoint ⇢ HTTP GET "/api/v1/test" [ExceptionHandlingWebHandler] Stack trace: at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsResolveContext.tryToFinishResolve(DnsResolveContext.java:966) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsResolveContext.query(DnsResolveContext.java:414) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsResolveContext.access$600(DnsResolveContext.java:63) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsResolveContext$2.operationComplete(DnsResolveContext.java:463) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:578) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:571) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:550) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:491) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:616) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.setFailure0(DefaultPromise.java:609) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:117) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsQueryContext.tryFailure(DnsQueryContext.java:225) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.resolver.dns.DnsQueryContext$4.run(DnsQueryContext.java:177) ~[netty-resolver-dns-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:170) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.AbstractEventExecutor.safeExecute$$$capture(AbstractEventExecutor.java:164) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500) ~[netty-transport-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.58.Final.jar:4.1.58.Final] at java.base/java.lang.Thread.run(Thread.java:845) ~[na:na] Caused by: io.netty.resolver.dns.DnsNameResolverTimeoutException: [/0.0.0.0:53] query via UDP timed out after 5000 milliseconds (no stack trace available) ``` ### Steps to reproduce 1. Build multi-module maven project: spring-cloud-dns-issue ./mvnw clean package 2. Run all microservices ./mvnw -pl discovery spring-boot:run ./mvnw -pl web spring-boot:run ./mvnw -pl api-gateway spring-boot:run 3. curl http://localhost:8080/api/v1/test ### Minimal yet complete reproducer code (or URL to code) https://github.com/rodmccutcheon/spring-cloud-dns-issue ### Netty version netty-resolver-dns-4.1.58.Final.jar ### JVM version (e.g. `java -version`) java --version openjdk 15.0.1 2020-10-20 OpenJDK Runtime Environment AdoptOpenJDK (build 15.0.1+9) Eclipse OpenJ9 VM AdoptOpenJDK (build openj9-0.23.0, JRE 15 Mac OS X amd64-64-Bit Compressed References 20201022_78 (JIT enabled, AOT enabled) OpenJ9 - 0394ef754 OMR - 582366ae5 JCL - ad583de3b5 based on jdk-15.0.1+9) ### OS version (e.g. `uname -a`) uname -a Darwin 192-168-1-107.tpgi.com.au 19.6.0 Darwin Kernel Version 19.6.0: Thu Oct 29 22:56:45 PDT 2020; root:xnu-6153.141.2.2~1/RELEASE_X86_64 x86_64
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java" ]
[]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java index 8ba95777b87..b9668dd3f5c 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java @@ -68,10 +68,12 @@ public Object run() { } } catch (ClassNotFoundException cause) { LOGGER.warn("Can not find {} in the classpath, fallback to system defaults. This may result in " - + "incorrect DNS resolutions on MacOS.", MACOS_PROVIDER_CLASS_NAME); + + "incorrect DNS resolutions on MacOS. Check whether you have a dependency on " + + "'io.netty:netty-resolver-dns-native-macos'", MACOS_PROVIDER_CLASS_NAME); } catch (Throwable cause) { LOGGER.error("Unable to load {}, fallback to system defaults. This may result in " - + "incorrect DNS resolutions on MacOS.", MACOS_PROVIDER_CLASS_NAME, cause); + + "incorrect DNS resolutions on MacOS. Check whether you have a dependency on " + + "'io.netty:netty-resolver-dns-native-macos'", MACOS_PROVIDER_CLASS_NAME, cause); constructor = null; } }
null
train
test
"2022-08-23T08:25:07"
"2021-02-12T04:45:51Z"
rodmccutcheon
val
netty/netty/12745_12746
netty/netty
netty/netty/12745
netty/netty/12746
[ "keyword_pr_to_issue" ]
617415ae3eb5cce1b6a4198157ede01b05a5a891
6c81a3fa025f31bc0308d7913f8ecbf540f99247
[ "Thanks for the report. This should be fixed by https://github.com/netty/netty/pull/12746", "Thank you for the quick fix!\r\n" ]
[]
"2022-08-26T23:58:59Z"
[]
Fallback to PemReader fails when BouncyCastlePemReader encounters an unsupported type
While I'm not completely certain this is a common scenario, we observed this failure on upgrading to Netty `4.1.80` and when using a custom bundle for a private key. From a quick glance, it looks like it should be resolved by ensuring that the input stream passed to the `BouncyCastlePemReader` is a copy, and processed independently of the original stream processed by `PemReader` ### Netty version 4.1.80 w/ tcnative 2.0.54 ### JVM version (e.g. `java -version`) openjdk version "17.0.4" 2022-07-19 LTS ### Expected behavior The PR https://github.com/netty/netty/pull/12670 introduced a change that enforces eager parsing by `BouncyCastlePemReader` when the classpath includes the `BouncyCastleProvider` The intended behavior should be the fallback to `PemReader` kicking in when the key type does not match one of the supported variants. ### Actual behavior In the case where there is a `BouncyCastleProvider` on the classpath, but the key type is of a format that is not supported by `BouncyCastlePemReader`, the **input stream has already been read**. This renders the fallback to trigger, but fails decoding. ``` Caused by: java.lang.IllegalArgumentException: Input stream does not contain valid private key. at io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:416) at io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:341) at io.netty.handler.ssl.SslContextBuilder.forServer(SslContextBuilder.java:84) .... Caused by: java.security.KeyException: could not find a PKCS #8 private key in input stream (see https://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information) at io.netty.handler.ssl.PemReader.keyNotFoundException(PemReader.java:156) at io.netty.handler.ssl.PemReader.readPrivateKey(PemReader.java:137) at io.netty.handler.ssl.SslContext.toPrivateKey(SslContext.java:1152) at io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:414) ``` ### Steps to reproduce Use a key with a format not supported by the `BouncyCastlePemReader`, and trigger the fallback logic.
[ "handler/src/main/java/io/netty/handler/ssl/SslContext.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslContext.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslContext.java b/handler/src/main/java/io/netty/handler/ssl/SslContext.java index efb8e36b4b8..dc898915da7 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslContext.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslContext.java @@ -28,6 +28,7 @@ import io.netty.util.DefaultAttributeMap; import io.netty.util.internal.EmptyArrays; +import java.io.BufferedInputStream; import java.security.Provider; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -1143,10 +1144,17 @@ protected static PrivateKey toPrivateKey(InputStream keyInputStream, String keyP // try BC first, if this fail fallback to original key extraction process if (BouncyCastlePemReader.isAvailable()) { + if (!keyInputStream.markSupported()) { + // We need an input stream that supports resetting, in case BouncyCastle fails to read. + keyInputStream = new BufferedInputStream(keyInputStream); + } + keyInputStream.mark(1048576); // Be able to reset up to 1 MiB of data. PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyInputStream, keyPassword); if (pk != null) { return pk; } + // BouncyCastle could not read the key. Reset the input stream in case the input position changed. + keyInputStream.reset(); } return getPrivateKeyFromByteBuffer(PemReader.readPrivateKey(keyInputStream), keyPassword);
null
train
test
"2022-08-26T13:53:34"
"2022-08-26T23:07:17Z"
argha-c
val
netty/netty/12787_12790
netty/netty
netty/netty/12787
netty/netty/12790
[ "keyword_pr_to_issue" ]
ef4a9dffeb3004a51b89e72330bd309a875f58e3
1440435865aa86a350094881b31005cb232424fc
[ "Thanks for the report." ]
[]
"2022-09-09T18:39:30Z"
[]
NPE with Paranoid leak detector and using a ByteProcessor on a CompositeBuffer of CompositeBuffer
### Expected behavior No exception ### Actual behavior Getting a NullPointerException ``` Caused by: java.lang.NullPointerException at io.netty.buffer.CompositeByteBuf.toComponentIndex0(CompositeByteBuf.java:930) at io.netty.buffer.CompositeByteBuf.forEachByteAsc0(CompositeByteBuf.java:672) at io.netty.buffer.CompositeByteBuf.forEachByteAsc0(CompositeByteBuf.java:682) at io.netty.buffer.AbstractByteBuf.forEachByte(AbstractByteBuf.java:1281) at io.netty.buffer.WrappedCompositeByteBuf.forEachByte(WrappedCompositeByteBuf.java:393) at io.netty.buffer.AdvancedLeakAwareCompositeByteBuf.forEachByte(AdvancedLeakAwareCompositeByteBuf.java:657) ``` ### Steps to reproduce * set ResourceLeakDetector in Paranoid mode * create a CompositeBuffer of CompositeBuffer of Buffers * run a ByteProcessor on the ByteBuf ### Minimal yet complete reproducer code (or URL to code) [netty-paranoid-leak.zip](https://github.com/netty/netty/files/9535586/netty-paranoid-leak.zip) ### Netty version 4.1.81.Final ### JVM version (e.g. `java -version`) 11.0.16 ### OS version (e.g. `uname -a`) Ubuntu 20.04.5 LTS
[ "buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java" ]
[ "buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java" ]
[ "buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java" ]
diff --git a/buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java b/buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java index faef8f88b2a..5a31a5e9b40 100644 --- a/buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java +++ b/buffer/src/main/java/io/netty/buffer/WrappedCompositeByteBuf.java @@ -408,6 +408,16 @@ public int forEachByteDesc(int index, int length, ByteProcessor processor) { return wrapped.forEachByteDesc(index, length, processor); } + @Override + protected int forEachByteAsc0(int start, int end, ByteProcessor processor) throws Exception { + return wrapped.forEachByteAsc0(start, end, processor); + } + + @Override + protected int forEachByteDesc0(int rStart, int rEnd, ByteProcessor processor) throws Exception { + return wrapped.forEachByteDesc0(rStart, rEnd, processor); + } + @Override public final int hashCode() { return wrapped.hashCode();
diff --git a/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java b/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java index 20567176158..4bb21b15b19 100644 --- a/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java +++ b/buffer/src/test/java/io/netty/buffer/AbstractCompositeByteBufTest.java @@ -15,6 +15,7 @@ */ package io.netty.buffer; +import io.netty.util.ByteProcessor; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.PlatformDependent; @@ -1774,4 +1775,36 @@ public void sliceOfCompositeBufferMustThrowISEAfterDiscardBytes() { composite.release(); } } + + @Test + public void forEachByteOnNestedCompositeByteBufMustSeeEntireFlattenedContents() { + CompositeByteBuf buf = newCompositeBuffer(); + buf.addComponent(true, newCompositeBuffer().addComponents( + true, + wrappedBuffer(new byte[] {1, 2, 3}), + wrappedBuffer(new byte[] {4, 5, 6}))); + final byte[] arrayAsc = new byte[6]; + final byte[] arrayDesc = new byte[6]; + buf.forEachByte(new ByteProcessor() { + int index; + + @Override + public boolean process(byte value) throws Exception { + arrayAsc[index++] = value; + return true; + } + }); + buf.forEachByteDesc(new ByteProcessor() { + int index; + + @Override + public boolean process(byte value) throws Exception { + arrayDesc[index++] = value; + return true; + } + }); + assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6}, arrayAsc); + assertArrayEquals(new byte[] {6, 5, 4, 3, 2, 1}, arrayDesc); + buf.release(); + } }
train
test
"2022-09-09T19:45:15"
"2022-09-09T13:06:22Z"
mederel
val
netty/netty/12798_12799
netty/netty
netty/netty/12798
netty/netty/12799
[ "keyword_pr_to_issue" ]
75982ea652eee022287c0af29ed629be4d0a1bfd
570c5d75bd172fbb2f6f68685326d4acb3978482
[ "Just verified that the validation is fine for Safari but fails with Firefox." ]
[]
"2022-09-13T01:27:13Z"
[]
Chrome/Firefox send `upgrade-insecure-requests` header
https://github.com/netty/netty/pull/12755 is unfortunately breaking Chrome and Firefox which both (rightly or wrongly) send the `upgrade-insecure-requests` header: ``` [DEBUG|2022-09-13 10:23:29.419|netty-worker1 ||io.netty.handler.codec.http2.Http2FrameCodec] Stream exception thrown for unknown stream 1. io.netty.handler.codec.http2.Http2Exception$StreamException: Illegal connection-specific header 'upgrade-insecure-requests' encountered. at io.netty.handler.codec.http2.Http2Exception.streamError(Http2Exception.java:153) at io.netty.handler.codec.http2.HpackDecoder.validate(HpackDecoder.java:412) at io.netty.handler.codec.http2.HpackDecoder.access$000(HpackDecoder.java:56) at io.netty.handler.codec.http2.HpackDecoder$Http2HeadersSink.appendToHeaderList(HpackDecoder.java:639) at io.netty.handler.codec.http2.HpackDecoder.insertHeader(HpackDecoder.java:506) at io.netty.handler.codec.http2.HpackDecoder.decode(HpackDecoder.java:294) at io.netty.handler.codec.http2.HpackDecoder.decode(HpackDecoder.java:131) ``` With Netty 4.1.80 and below I was able to run with `validateHeaders(true)` (the default). However with Netty 4.1.81 the only work around I've found is; ``` Http2FrameCodecBuilder builder = Http2FrameCodecBuilder.forServer(); builder.validateHeaders(false); ``` @chrisvest My thanks for implementing these extra validations. And my thanks too for helping me investigate this. I am running with a particularly restrictive 'Content-Security-Policy' header - but that doesn't seem to be related as the exception above occurs well before a cache-clean web-browser sends the `upgrade-insecure-requests` header.
[ "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/DefaultHttp2HeadersDecoderTest.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 cf474fce584..9d2bd875be8 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 @@ -422,13 +422,12 @@ private static HeaderType validate(int streamId, CharSequence name, @SuppressWarnings("deprecation") // We need to check for deprecated headers as well. private static boolean isConnectionHeader(CharSequence name) { - // These are the known standard and non-standard connection related headers: + // These are the known standard connection related headers: // - upgrade (7 chars) // - connection (10 chars) // - keep-alive (10 chars) // - proxy-connection (16 chars) // - transfer-encoding (17 chars) - // - upgrade-insecure-requests (25 chars) // // We scan for these based on the length, then double-check any matching name. int len = name.length(); @@ -449,7 +448,7 @@ private static boolean isConnectionHeader(CharSequence name) { if (len == 16) { return contentEqualsIgnoreCase(name, HttpHeaderNames.PROXY_CONNECTION); } - return len == 25 && contentEqualsIgnoreCase(name, HttpHeaderNames.UPGRADE_INSECURE_REQUESTS); + return false; } private static boolean contains(Http2Headers headers, CharSequence name) {
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoderTest.java index 1b25fea70fc..ec5c4a23ef6 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2HeadersDecoderTest.java @@ -167,9 +167,6 @@ public void decodingConnectionRelatedHeadersMustFailValidation() throws Exceptio // Non-standard connection related headers: verifyValidationFails(decoder, encode(b(":method"), b("GET"), b("proxy-connection"), b("keep-alive"))); - verifyValidationFails(decoder, encode(b(":method"), b("GET"), b("upgrade-insecure-requests"), b("1"))); - verifyValidationFails(decoder, encode(b(":method"), b("GET"), - b("content-security-policy"), b("upgrade-insecure-requests"), b("upgrade-insecure-requests"), b("1"))); // Only "trailers" is allowed for the TE header: verifyValidationFails(decoder, encode(b(":method"), b("GET"), b("te"), b("compress")));
val
test
"2022-09-12T20:29:08"
"2022-09-13T00:57:02Z"
glennosss
val
netty/netty/12933_12941
netty/netty
netty/netty/12933
netty/netty/12941
[ "keyword_issue_to_pr" ]
dd671fc3e04d037dbfb9c9b3bf5577b4ce90d2a1
ae9b82388e49cdc904e0ef4e81439486105d9d30
[ "\r\nMissing: header-> origin", "Please explain in more detail.", "When the websocketclient connection request header is missing the origin, a null pointer problem will occur", "@amizurov What's your take? Do we need validation to check for the origin header somewhere?", "Now he throws a null pointer. I think we can give some warning logs", "Hi @heixiaoma , @chrisvest. Let me take a look.", "@heixiaoma Could you please clarify, did you set `webSocketURL` -> \"/ws\" via constructor and `customHeaders` which contains `Host` but does not contain `Origin` header ?", "> @heixiaoma 您能否澄清一下,您是否`webSocketURL`通过构造函数设置了 -> \"/ws\" 并且`customHeaders`包含`Host`但不包含`Origin`header ?\r\n\r\nyes", "So the main problem here, that if we pass the `webSocketURL` without host (e.g. '/ws') we faced with NPE even when we building the `Host` header value. But if we pass the `Host` header value via `customHeaders` everything should works fine, but now we got the NPE on the building `Origin` header value (see https://github.com/netty/netty/issues/9673). \r\n\r\nI created the PR which should fix the `Origin` header behaviour (https://github.com/netty/netty/pull/12941). Also i think we can add additional check that if `webSocketURL` does not contain host and `Host` header does not present in custom headers we throw an invalid arg exception. @chrisvest WDYT ?\r\n\r\n", "@amizurov Sounds good. Do you want to add that check to https://github.com/netty/netty/pull/12941, or in a different PR?", "> @amizurov Sounds good. Do you want to add that check to https://github.com/netty/netty/pull/12941, or in a different PR?\n\nAdded to https://github.com/netty/netty/pull/12941", "I think this was fixed by #12941" ]
[ "This is an odd usage of assertThrows:\r\n\r\n```suggestion\r\n assertInstanceOf(IllegalArgumentException.class, handshakeFuture.cause());\r\n```", "This is an odd usage of assertThrows:\r\n\r\n```suggestion\r\n assertInstanceOf(IllegalArgumentException.class, handshakeFuture.cause());\r\n```\r\n```", "Done", "Done" ]
"2022-10-31T11:23:19Z"
[]
WebSocketClientHandshaker java.lang.NullPointerException
WebSocketClientHandshaker ![1666764902075](https://user-images.githubusercontent.com/10923974/197948891-0bc9490a-8b02-4d0f-bc49-506fcb1a0d11.png)
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.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/WebSocketClientHandshaker.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java", "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolHandler.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00Test.java", "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07Test.java", "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08Test.java", "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13Test.java", "codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java index e5ff31c6d94..2df036ac0a8 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker.java @@ -85,6 +85,8 @@ public abstract class WebSocketClientHandshaker { private final boolean absoluteUpgradeUrl; + protected final boolean generateOriginHeader; + /** * Base constructor * @@ -151,6 +153,36 @@ protected WebSocketClientHandshaker(URI uri, WebSocketVersion version, String su protected WebSocketClientHandshaker(URI uri, WebSocketVersion version, String subprotocol, HttpHeaders customHeaders, int maxFramePayloadLength, long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) { + this(uri, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, + absoluteUpgradeUrl, true); + } + + /** + * Base constructor + * + * @param uri + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate the `Origin`|`Sec-WebSocket-Origin` header value for handshake request + * according to the given webSocketURL + */ + protected WebSocketClientHandshaker(URI uri, WebSocketVersion version, String subprotocol, + HttpHeaders customHeaders, int maxFramePayloadLength, + long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl, boolean generateOriginHeader) { this.uri = uri; this.version = version; expectedSubprotocol = subprotocol; @@ -158,6 +190,7 @@ protected WebSocketClientHandshaker(URI uri, WebSocketVersion version, String su this.maxFramePayloadLength = maxFramePayloadLength; this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; this.absoluteUpgradeUrl = absoluteUpgradeUrl; + this.generateOriginHeader = generateOriginHeader; } /** @@ -265,6 +298,28 @@ public final ChannelFuture handshake(Channel channel, final ChannelPromise promi } } + if (uri.getHost() == null) { + if (customHeaders == null || !customHeaders.contains(HttpHeaderNames.HOST)) { + promise.setFailure(new IllegalArgumentException("Cannot generate the 'host' header value," + + " webSocketURI should contain host or passed through customHeaders")); + return promise; + } + + if (generateOriginHeader && !customHeaders.contains(HttpHeaderNames.ORIGIN)) { + final String originName; + if (version == WebSocketVersion.V07 || version == WebSocketVersion.V08) { + originName = HttpHeaderNames.SEC_WEBSOCKET_ORIGIN.toString(); + } else { + originName = HttpHeaderNames.ORIGIN.toString(); + } + + promise.setFailure(new IllegalArgumentException("Cannot generate the '" + originName + "' header" + + " value, webSocketURI should contain host or disable generateOriginHeader or pass value" + + " through customHeaders")); + return promise; + } + } + FullHttpRequest request = newHandshakeRequest(); channel.writeAndFlush(request).addListener(new ChannelFutureListener() { diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java index 9ccee77af1c..6b63e38f24f 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00.java @@ -109,11 +109,42 @@ public WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, S * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over * clear HTTP */ + WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subprotocol, + HttpHeaders customHeaders, int maxFramePayloadLength, + long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) { + this(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, + absoluteUpgradeUrl, true); + } + + /** + * Creates a new instance with the specified destination WebSocket location and version to initiate. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate the `Origin` header value for handshake request + * according to the given webSocketURL + */ WebSocketClientHandshaker00(URI webSocketURL, WebSocketVersion version, String subprotocol, HttpHeaders customHeaders, int maxFramePayloadLength, - long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) { + long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl, + boolean generateOriginHeader) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); } /** @@ -182,15 +213,22 @@ protected FullHttpRequest newHandshakeRequest() { if (customHeaders != null) { headers.add(customHeaders); + if (!headers.contains(HttpHeaderNames.HOST)) { + // Only add HOST header if customHeaders did not contain it. + // + // See https://github.com/netty/netty/issues/10101 + headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL)); + } + } else { + headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL)); } headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET) .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) - .set(HttpHeaderNames.HOST, websocketHostValue(wsURL)) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2); - if (!headers.contains(HttpHeaderNames.ORIGIN)) { + if (generateOriginHeader && !headers.contains(HttpHeaderNames.ORIGIN)) { headers.set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL)); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java index 924978a256b..b0d1ace3628 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07.java @@ -164,12 +164,52 @@ public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, S * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over * clear HTTP */ + WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol, + boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, + boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis, + boolean absoluteUpgradeUrl) { + this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking, + allowMaskMismatch, forceCloseTimeoutMillis, absoluteUpgradeUrl, true); + } + + /** + * Creates a new instance. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + * @param performMasking + * Whether to mask all written websocket frames. This must be set to true in order to be fully compatible + * with the websocket specifications. Client applications that communicate with a non-standard server + * which doesn't require masking might set this to false to achieve a higher performance. + * @param allowMaskMismatch + * When set to true, frames which are not masked properly according to the standard will still be + * accepted + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified. + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate a `Sec-WebSocket-Origin` header value for handshake request + * according to the given webSocketURL + */ WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); this.allowExtensions = allowExtensions; this.performMasking = performMasking; this.allowMaskMismatch = allowMaskMismatch; @@ -232,7 +272,7 @@ protected FullHttpRequest newHandshakeRequest() { .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key); - if (!headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) { + if (generateOriginHeader && !headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL)); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java index f24e7c469ad..8f2f7b7c0cd 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08.java @@ -134,7 +134,7 @@ public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, S boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis) { this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking, - allowMaskMismatch, forceCloseTimeoutMillis, false); + allowMaskMismatch, forceCloseTimeoutMillis, false, true); } /** @@ -166,12 +166,52 @@ public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, S * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over * clear HTTP */ + WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol, + boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, + boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis, + boolean absoluteUpgradeUrl) { + this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking, + allowMaskMismatch, forceCloseTimeoutMillis, absoluteUpgradeUrl, true); + } + + /** + * Creates a new instance. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + * @param performMasking + * Whether to mask all written websocket frames. This must be set to true in order to be fully compatible + * with the websocket specifications. Client applications that communicate with a non-standard server + * which doesn't require masking might set this to false to achieve a higher performance. + * @param allowMaskMismatch + * When set to true, frames which are not masked properly according to the standard will still be + * accepted + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified. + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate a `Sec-WebSocket-Origin` header value for handshake request + * according to the given webSocketURL + */ WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); this.allowExtensions = allowExtensions; this.performMasking = performMasking; this.allowMaskMismatch = allowMaskMismatch; @@ -234,7 +274,7 @@ protected FullHttpRequest newHandshakeRequest() { .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key); - if (!headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) { + if (generateOriginHeader && !headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL)); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java index 70805611fa5..6e47607c02e 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java @@ -167,12 +167,53 @@ public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, S * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over * clear HTTP */ + WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol, + boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, + boolean performMasking, boolean allowMaskMismatch, + long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) { + this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking, + allowMaskMismatch, forceCloseTimeoutMillis, absoluteUpgradeUrl, true); + } + + /** + * Creates a new instance. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be + * sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param customHeaders + * Map of custom headers to add to the client request + * @param maxFramePayloadLength + * Maximum length of a frame's payload + * @param performMasking + * Whether to mask all written websocket frames. This must be set to true in order to be fully compatible + * with the websocket specifications. Client applications that communicate with a non-standard server + * which doesn't require masking might set this to false to achieve a higher performance. + * @param allowMaskMismatch + * When set to true, frames which are not masked properly according to the standard will still be + * accepted + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified. + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate the `Origin` header value for handshake request + * according to the given webSocketURL + */ WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol, boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, boolean performMasking, boolean allowMaskMismatch, - long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) { + long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl, + boolean generateOriginHeader) { super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); this.allowExtensions = allowExtensions; this.performMasking = performMasking; this.allowMaskMismatch = allowMaskMismatch; @@ -190,7 +231,6 @@ public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, S * Upgrade: websocket * Connection: Upgrade * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== - * Origin: http://example.com * Sec-WebSocket-Protocol: chat, superchat * Sec-WebSocket-Version: 13 * </pre> @@ -235,7 +275,7 @@ protected FullHttpRequest newHandshakeRequest() { .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE) .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key); - if (!headers.contains(HttpHeaderNames.ORIGIN)) { + if (generateOriginHeader && !headers.contains(HttpHeaderNames.ORIGIN)) { headers.set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL)); } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java index a5dabdcbd55..ce915eb3986 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerFactory.java @@ -222,4 +222,69 @@ public static WebSocketClientHandshaker newHandshaker( throw new WebSocketClientHandshakeException("Protocol version " + version + " not supported."); } + + /** + * Creates a new handshaker. + * + * @param webSocketURL + * URL for web socket communications. e.g "ws://myhost.com/mypath". + * Subsequent web socket frames will be sent to this URL. + * @param version + * Version of web socket specification to use to connect to the server + * @param subprotocol + * Sub protocol request sent to the server. Null if no sub-protocol support is required. + * @param allowExtensions + * Allow extensions to be used in the reserved bits of the web socket frame + * @param customHeaders + * Custom HTTP headers to send during the handshake + * @param maxFramePayloadLength + * Maximum allowable frame payload length. Setting this value to your application's + * requirement may reduce denial of service attacks using long data frames. + * @param performMasking + * Whether to mask all written websocket frames. This must be set to true in order to be fully compatible + * with the websocket specifications. Client applications that communicate with a non-standard server + * which doesn't require masking might set this to false to achieve a higher performance. + * @param allowMaskMismatch + * When set to true, frames which are not masked properly according to the standard will still be + * accepted. + * @param forceCloseTimeoutMillis + * Close the connection if it was not closed by the server after timeout specified + * @param absoluteUpgradeUrl + * Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over + * clear HTTP + * @param generateOriginHeader + * Allows to generate the `Origin`|`Sec-WebSocket-Origin` header value for handshake request + * according to the given webSocketURL + */ + public static WebSocketClientHandshaker newHandshaker( + URI webSocketURL, WebSocketVersion version, String subprotocol, + boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength, + boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis, + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { + if (version == V13) { + return new WebSocketClientHandshaker13( + webSocketURL, V13, subprotocol, allowExtensions, customHeaders, + maxFramePayloadLength, performMasking, allowMaskMismatch, forceCloseTimeoutMillis, + absoluteUpgradeUrl, generateOriginHeader); + } + if (version == V08) { + return new WebSocketClientHandshaker08( + webSocketURL, V08, subprotocol, allowExtensions, customHeaders, + maxFramePayloadLength, performMasking, allowMaskMismatch, forceCloseTimeoutMillis, + absoluteUpgradeUrl, generateOriginHeader); + } + if (version == V07) { + return new WebSocketClientHandshaker07( + webSocketURL, V07, subprotocol, allowExtensions, customHeaders, + maxFramePayloadLength, performMasking, allowMaskMismatch, forceCloseTimeoutMillis, + absoluteUpgradeUrl, generateOriginHeader); + } + if (version == V00) { + return new WebSocketClientHandshaker00( + webSocketURL, V00, subprotocol, customHeaders, + maxFramePayloadLength, forceCloseTimeoutMillis, absoluteUpgradeUrl, generateOriginHeader); + } + + throw new WebSocketClientHandshakeException("Protocol version " + version + " not supported."); + } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java index 0cfd6c39db8..6700c7818ad 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java @@ -34,6 +34,7 @@ public final class WebSocketClientProtocolConfig { static final boolean DEFAULT_ALLOW_MASK_MISMATCH = false; static final boolean DEFAULT_HANDLE_CLOSE_FRAMES = true; static final boolean DEFAULT_DROP_PONG_FRAMES = true; + static final boolean DEFAULT_GENERATE_ORIGIN_HEADER = true; private final URI webSocketUri; private final String subprotocol; @@ -49,6 +50,7 @@ public final class WebSocketClientProtocolConfig { private final long handshakeTimeoutMillis; private final long forceCloseTimeoutMillis; private final boolean absoluteUpgradeUrl; + private final boolean generateOriginHeader; private WebSocketClientProtocolConfig( URI webSocketUri, @@ -64,7 +66,8 @@ private WebSocketClientProtocolConfig( boolean dropPongFrames, long handshakeTimeoutMillis, long forceCloseTimeoutMillis, - boolean absoluteUpgradeUrl + boolean absoluteUpgradeUrl, + boolean generateOriginHeader ) { this.webSocketUri = webSocketUri; this.subprotocol = subprotocol; @@ -80,6 +83,7 @@ private WebSocketClientProtocolConfig( this.dropPongFrames = dropPongFrames; this.handshakeTimeoutMillis = checkPositive(handshakeTimeoutMillis, "handshakeTimeoutMillis"); this.absoluteUpgradeUrl = absoluteUpgradeUrl; + this.generateOriginHeader = generateOriginHeader; } public URI webSocketUri() { @@ -138,24 +142,29 @@ public boolean absoluteUpgradeUrl() { return absoluteUpgradeUrl; } + public boolean generateOriginHeader() { + return generateOriginHeader; + } + @Override public String toString() { return "WebSocketClientProtocolConfig" + - " {webSocketUri=" + webSocketUri + - ", subprotocol=" + subprotocol + - ", version=" + version + - ", allowExtensions=" + allowExtensions + - ", customHeaders=" + customHeaders + - ", maxFramePayloadLength=" + maxFramePayloadLength + - ", performMasking=" + performMasking + - ", allowMaskMismatch=" + allowMaskMismatch + - ", handleCloseFrames=" + handleCloseFrames + - ", sendCloseFrame=" + sendCloseFrame + - ", dropPongFrames=" + dropPongFrames + - ", handshakeTimeoutMillis=" + handshakeTimeoutMillis + - ", forceCloseTimeoutMillis=" + forceCloseTimeoutMillis + - ", absoluteUpgradeUrl=" + absoluteUpgradeUrl + - "}"; + " {webSocketUri=" + webSocketUri + + ", subprotocol=" + subprotocol + + ", version=" + version + + ", allowExtensions=" + allowExtensions + + ", customHeaders=" + customHeaders + + ", maxFramePayloadLength=" + maxFramePayloadLength + + ", performMasking=" + performMasking + + ", allowMaskMismatch=" + allowMaskMismatch + + ", handleCloseFrames=" + handleCloseFrames + + ", sendCloseFrame=" + sendCloseFrame + + ", dropPongFrames=" + dropPongFrames + + ", handshakeTimeoutMillis=" + handshakeTimeoutMillis + + ", forceCloseTimeoutMillis=" + forceCloseTimeoutMillis + + ", absoluteUpgradeUrl=" + absoluteUpgradeUrl + + ", generateOriginHeader=" + generateOriginHeader + + "}"; } public Builder toBuilder() { @@ -177,7 +186,8 @@ public static Builder newBuilder() { DEFAULT_DROP_PONG_FRAMES, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS, -1, - false); + false, + DEFAULT_GENERATE_ORIGIN_HEADER); } public static final class Builder { @@ -195,6 +205,7 @@ public static final class Builder { private long handshakeTimeoutMillis; private long forceCloseTimeoutMillis; private boolean absoluteUpgradeUrl; + private boolean generateOriginHeader; private Builder(WebSocketClientProtocolConfig clientConfig) { this(ObjectUtil.checkNotNull(clientConfig, "clientConfig").webSocketUri(), @@ -210,7 +221,8 @@ private Builder(WebSocketClientProtocolConfig clientConfig) { clientConfig.dropPongFrames(), clientConfig.handshakeTimeoutMillis(), clientConfig.forceCloseTimeoutMillis(), - clientConfig.absoluteUpgradeUrl()); + clientConfig.absoluteUpgradeUrl(), + clientConfig.generateOriginHeader()); } private Builder(URI webSocketUri, @@ -226,7 +238,8 @@ private Builder(URI webSocketUri, boolean dropPongFrames, long handshakeTimeoutMillis, long forceCloseTimeoutMillis, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, + boolean generateOriginHeader) { this.webSocketUri = webSocketUri; this.subprotocol = subprotocol; this.version = version; @@ -241,6 +254,7 @@ private Builder(URI webSocketUri, this.handshakeTimeoutMillis = handshakeTimeoutMillis; this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; this.absoluteUpgradeUrl = absoluteUpgradeUrl; + this.generateOriginHeader = generateOriginHeader; } /** @@ -367,6 +381,16 @@ public Builder absoluteUpgradeUrl(boolean absoluteUpgradeUrl) { return this; } + /** + * Allows to generate the `Origin`|`Sec-WebSocket-Origin` header value for handshake request + * according the given webSocketURI. Usually it's not necessary and can be disabled, + * but for backward compatibility is set to {@code true} as default. + */ + public Builder generateOriginHeader(boolean generateOriginHeader) { + this.generateOriginHeader = generateOriginHeader; + return this; + } + /** * Build unmodifiable client protocol configuration. */ @@ -385,7 +409,8 @@ public WebSocketClientProtocolConfig build() { dropPongFrames, handshakeTimeoutMillis, forceCloseTimeoutMillis, - absoluteUpgradeUrl + absoluteUpgradeUrl, + generateOriginHeader ); } } 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 257d3f025c9..2f8e262ca0a 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 @@ -94,7 +94,8 @@ public WebSocketClientProtocolHandler(WebSocketClientProtocolConfig clientConfig clientConfig.performMasking(), clientConfig.allowMaskMismatch(), clientConfig.forceCloseTimeoutMillis(), - clientConfig.absoluteUpgradeUrl() + clientConfig.absoluteUpgradeUrl(), + clientConfig.generateOriginHeader() ); this.clientConfig = clientConfig; }
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00Test.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00Test.java index 9d1606f3707..d84c9032c2a 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00Test.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker00Test.java @@ -23,9 +23,9 @@ public class WebSocketClientHandshaker00Test extends WebSocketClientHandshakerTest { @Override protected WebSocketClientHandshaker newHandshaker(URI uri, String subprotocol, HttpHeaders headers, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { return new WebSocketClientHandshaker00(uri, WebSocketVersion.V00, subprotocol, headers, - 1024, 10000, absoluteUpgradeUrl); + 1024, 10000, absoluteUpgradeUrl, generateOriginHeader); } @Override diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07Test.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07Test.java index 692bc3bbe64..e3f04da85f2 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07Test.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker07Test.java @@ -31,7 +31,7 @@ public class WebSocketClientHandshaker07Test extends WebSocketClientHandshakerTe public void testHostHeaderPreserved() { URI uri = URI.create("ws://localhost:9999"); WebSocketClientHandshaker handshaker = newHandshaker(uri, null, - new DefaultHttpHeaders().set(HttpHeaderNames.HOST, "test.netty.io"), false); + new DefaultHttpHeaders().set(HttpHeaderNames.HOST, "test.netty.io"), false, true); FullHttpRequest request = handshaker.newHandshakeRequest(); try { @@ -44,10 +44,10 @@ public void testHostHeaderPreserved() { @Override protected WebSocketClientHandshaker newHandshaker(URI uri, String subprotocol, HttpHeaders headers, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { return new WebSocketClientHandshaker07(uri, WebSocketVersion.V07, subprotocol, false, headers, 1024, true, false, 10000, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); } @Override diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08Test.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08Test.java index 34c5fb76d8b..aa8e11dd50a 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08Test.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker08Test.java @@ -22,9 +22,9 @@ public class WebSocketClientHandshaker08Test extends WebSocketClientHandshaker07Test { @Override protected WebSocketClientHandshaker newHandshaker(URI uri, String subprotocol, HttpHeaders headers, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { return new WebSocketClientHandshaker08(uri, WebSocketVersion.V08, subprotocol, false, headers, 1024, true, true, 10000, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); } } diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13Test.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13Test.java index 2371caed598..cd82f214546 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13Test.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13Test.java @@ -24,10 +24,10 @@ public class WebSocketClientHandshaker13Test extends WebSocketClientHandshaker07 @Override protected WebSocketClientHandshaker newHandshaker(URI uri, String subprotocol, HttpHeaders headers, - boolean absoluteUpgradeUrl) { + boolean absoluteUpgradeUrl, boolean generateOriginHeader) { return new WebSocketClientHandshaker13(uri, WebSocketVersion.V13, subprotocol, false, headers, 1024, true, true, 10000, - absoluteUpgradeUrl); + absoluteUpgradeUrl, generateOriginHeader); } @Override diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerTest.java index 1be884e0b66..411e8ae9c2a 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshakerTest.java @@ -51,6 +51,7 @@ import static io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker13.WEBSOCKET_13_ACCEPT_GUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -59,10 +60,11 @@ public abstract class WebSocketClientHandshakerTest { protected abstract WebSocketClientHandshaker newHandshaker(URI uri, String subprotocol, HttpHeaders headers, - boolean absoluteUpgradeUrl); + boolean absoluteUpgradeUrl, + boolean generateOriginHeader); protected WebSocketClientHandshaker newHandshaker(URI uri) { - return newHandshaker(uri, null, null, false); + return newHandshaker(uri, null, null, false, true); } protected abstract CharSequence getOriginHeaderName(); @@ -183,7 +185,7 @@ public void originHeaderWithoutScheme() { public void testSetOriginFromCustomHeaders() { HttpHeaders customHeaders = new DefaultHttpHeaders().set(getOriginHeaderName(), "http://example.com"); WebSocketClientHandshaker handshaker = newHandshaker(URI.create("ws://server.example.com/chat"), null, - customHeaders, false); + customHeaders, false, true); FullHttpRequest request = handshaker.newHandshakeRequest(); try { assertEquals("http://example.com", request.headers().get(getOriginHeaderName())); @@ -192,6 +194,50 @@ public void testSetOriginFromCustomHeaders() { } } + @Test + public void testOriginHeaderIsAbsentWhenGeneratingDisable() { + URI uri = URI.create("http://example.com/ws"); + WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, false, false); + FullHttpRequest request = handshaker.newHandshakeRequest(); + try { + assertFalse(request.headers().contains(getOriginHeaderName())); + assertEquals("/ws", request.uri()); + } finally { + request.release(); + } + } + + @Test + public void testInvalidHostWhenIncorrectWebSocketURI() { + URI uri = URI.create("/ws"); + EmbeddedChannel channel = new EmbeddedChannel(new HttpClientCodec()); + final WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, false, true); + final ChannelFuture handshakeFuture = handshaker.handshake(channel); + + assertFalse(handshakeFuture.isSuccess()); + assertInstanceOf(IllegalArgumentException.class, handshakeFuture.cause()); + assertEquals("Cannot generate the 'host' header value, webSocketURI should contain host" + + " or passed through customHeaders", handshakeFuture.cause().getMessage()); + assertFalse(channel.finish()); + } + + @Test + public void testInvalidOriginWhenIncorrectWebSocketURI() { + URI uri = URI.create("/ws"); + EmbeddedChannel channel = new EmbeddedChannel(new HttpClientCodec()); + HttpHeaders headers = new DefaultHttpHeaders(); + headers.set(HttpHeaderNames.HOST, "localhost:80"); + final WebSocketClientHandshaker handshaker = newHandshaker(uri, null, headers, false, true); + final ChannelFuture handshakeFuture = handshaker.handshake(channel); + + assertFalse(handshakeFuture.isSuccess()); + assertInstanceOf(IllegalArgumentException.class, handshakeFuture.cause()); + assertEquals("Cannot generate the '" + getOriginHeaderName() + "' header value," + + " webSocketURI should contain host or disable generateOriginHeader" + + " or pass value through customHeaders", handshakeFuture.cause().getMessage()); + assertFalse(channel.finish()); + } + private void testHostHeader(String uri, String expected) { testHeaderDefaultHttp(uri, HttpHeaderNames.HOST, expected); } @@ -262,7 +308,7 @@ public void testUpgradeUrlWithoutPathWithQuery() { @Test public void testAbsoluteUpgradeUrlWithQuery() { URI uri = URI.create("ws://localhost:9999/path%20with%20ws?a=b%20c"); - WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, true); + WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, true, true); FullHttpRequest request = handshaker.newHandshakeRequest(); try { assertEquals("ws://localhost:9999/path%20with%20ws?a=b%20c", request.uri()); @@ -392,7 +438,7 @@ public void testDuplicateWebsocketHandshakeHeaders() { inputHeaders.add(getProtocolHeaderName(), bogusSubProtocol); String realSubProtocol = "realSubProtocol"; - WebSocketClientHandshaker handshaker = newHandshaker(uri, realSubProtocol, inputHeaders, false); + WebSocketClientHandshaker handshaker = newHandshaker(uri, realSubProtocol, inputHeaders, false, true); FullHttpRequest request = handshaker.newHandshakeRequest(); HttpHeaders outputHeaders = request.headers(); @@ -412,7 +458,7 @@ public void testDuplicateWebsocketHandshakeHeaders() { @Test public void testWebSocketClientHandshakeException() { URI uri = URI.create("ws://localhost:9999/exception"); - WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, false); + WebSocketClientHandshaker handshaker = newHandshaker(uri, null, null, false, true); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); response.headers().set(HttpHeaderNames.WWW_AUTHENTICATE, "realm = access token required");
train
test
"2022-10-31T11:40:45"
"2022-10-26T06:16:21Z"
heixiaoma
val
netty/netty/12959_12978
netty/netty
netty/netty/12959
netty/netty/12978
[ "keyword_pr_to_issue" ]
a4c37bc06d16ba2267a3f8cac151f29bd9118aad
ecf489fb75d25d0fd35992d53f2e9bc6d9861e47
[]
[]
"2022-11-08T22:14:45Z"
[]
Netty's BlockHound integration assumes `FastThreadLocalThread` is always non-blocking
### Expected behavior The motivation is similar to https://github.com/netty/netty/issues/12125 which has already been reported and closed. I'm wondering if `FastThreadLocalThread` can be used for executing blocking tasks while integrating with Netty's `BlockHound` integration. ### Actual behavior Some libraries utilize `FastThreadLocalThread` not only for event loops but also for blocking task executors. For this case, it is acceptable that a blocking task is executed within a `FastThreadLocalThread`. However, Netty's `BlockHound` integration assumes that all `FastThreadLocalThread` instances should be non-blocking. https://github.com/netty/netty/blob/cfcc5144578d3f998d353cc3c3b448fc56333e0d/common/src/main/java/io/netty/util/internal/Hidden.java#L173 I'm wondering if it would be possible to define a separate `FastThreadLocalThread` (e.g. `NonBlockingFastThreadLocalThread`) and apply `BlockHound` predicates on the `NonBlocking` variant instead. I guess users may override `DefaultThreadFactory#newThread` and apply their own `FastThreadLocalThread` variant if they would like. A potential diffset: ``` diff --git a/common/src/main/java/io/netty/util/concurrent/DefaultThreadFactory.java b/common/src/main/java/io/netty/util/concurrent/DefaultThreadFactory.java index a18f236309..6e2b25f67c 100644 --- a/common/src/main/java/io/netty/util/concurrent/DefaultThreadFactory.java +++ b/common/src/main/java/io/netty/util/concurrent/DefaultThreadFactory.java @@ -118,6 +118,6 @@ public class DefaultThreadFactory implements ThreadFactory { } protected Thread newThread(Runnable r, String name) { - return new FastThreadLocalThread(threadGroup, r, name); + return new NonBlockingFastThreadLocalThread(threadGroup, r, name); } } diff --git a/common/src/main/java/io/netty/util/concurrent/NonBlockingFastThreadLocalThread.java b/common/src/main/java/io/netty/util/concurrent/NonBlockingFastThreadLocalThread.java new file mode 100644 index 0000000000..00b2455e43 --- /dev/null +++ b/common/src/main/java/io/netty/util/concurrent/NonBlockingFastThreadLocalThread.java @@ -0,0 +1,31 @@ +/* + * Copyright 2022 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: + * + * https://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.concurrent; + +/** + * A special {@link Thread} that provides fast access to {@link FastThreadLocal} variables. + */ +public final class NonBlockingFastThreadLocalThread extends FastThreadLocalThread { + + public NonBlockingFastThreadLocalThread(ThreadGroup threadGroup, Runnable r, String name) { + super(threadGroup, r, name); + } + + public NonBlockingFastThreadLocalThread(Runnable runnable) { + super(runnable); + } +} diff --git a/common/src/main/java/io/netty/util/internal/Hidden.java b/common/src/main/java/io/netty/util/internal/Hidden.java index fec14d1254..4c67b7f166 100644 --- a/common/src/main/java/io/netty/util/internal/Hidden.java +++ b/common/src/main/java/io/netty/util/internal/Hidden.java @@ -16,13 +16,13 @@ package io.netty.util.internal; -import io.netty.util.concurrent.FastThreadLocalThread; -import reactor.blockhound.BlockHound; -import reactor.blockhound.integration.BlockHoundIntegration; - import java.util.function.Function; import java.util.function.Predicate; +import io.netty.util.concurrent.NonBlockingFastThreadLocalThread; +import reactor.blockhound.BlockHound; +import reactor.blockhound.integration.BlockHoundIntegration; + /** * Contains classes that must have public visibility but are not public API. */ @@ -170,7 +170,7 @@ class Hidden { @Override @SuppressJava6Requirement(reason = "Predicate#test") public boolean test(Thread thread) { - return p.test(thread) || thread instanceof FastThreadLocalThread; + return p.test(thread) || thread instanceof NonBlockingFastThreadLocalThread; } }; } 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 0eb7b3495f..e1e76e6688 100644 --- a/common/src/main/java/io/netty/util/internal/ObjectCleaner.java +++ b/common/src/main/java/io/netty/util/internal/ObjectCleaner.java @@ -15,7 +15,8 @@ */ package io.netty.util.internal; -import io.netty.util.concurrent.FastThreadLocalThread; +import static io.netty.util.internal.SystemPropertyUtil.getInt; +import static java.lang.Math.max; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; @@ -24,8 +25,7 @@ import java.security.PrivilegedAction; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import static io.netty.util.internal.SystemPropertyUtil.getInt; -import static java.lang.Math.max; +import io.netty.util.concurrent.NonBlockingFastThreadLocalThread; /** * Allows a way to register some {@link Runnable} that will executed once there are no references to an {@link Object} @@ -100,7 +100,7 @@ public final class ObjectCleaner { // Check if there is already a cleaner running. if (CLEANER_RUNNING.compareAndSet(false, true)) { - final Thread cleanupThread = new FastThreadLocalThread(CLEANER_TASK); + final Thread cleanupThread = new NonBlockingFastThreadLocalThread(CLEANER_TASK); cleanupThread.setPriority(Thread.MIN_PRIORITY); // Set to null to ensure we not create classloader leaks by holding a strong reference to the inherited // classloader. ``` ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.82 ### JVM version (e.g. `java -version`) n/a ### OS version (e.g. `uname -a`) n/a
[ "common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java", "common/src/main/java/io/netty/util/internal/Hidden.java" ]
[ "common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java", "common/src/main/java/io/netty/util/internal/Hidden.java" ]
[ "transport-blockhound-tests/src/test/java/io/netty/util/internal/NettyBlockHoundIntegrationTest.java" ]
diff --git a/common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java b/common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java index dcef6b28fda..9f7184ee9b5 100644 --- a/common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java +++ b/common/src/main/java/io/netty/util/concurrent/FastThreadLocalThread.java @@ -111,4 +111,18 @@ public static boolean willCleanupFastThreadLocals(Thread thread) { return thread instanceof FastThreadLocalThread && ((FastThreadLocalThread) thread).willCleanupFastThreadLocals(); } + + /** + * Query whether this thread is allowed to perform blocking calls or not. + * {@link FastThreadLocalThread}s are often used in event-loops, where blocking calls are forbidden in order to + * prevent event-loop stalls, so this method returns {@code false} by default. + * <p> + * Subclasses of {@link FastThreadLocalThread} can override this method if they are not meant to be used for + * running event-loops. + * + * @return {@code false}, unless overriden by a subclass. + */ + public boolean permitBlockingCalls() { + return false; + } } diff --git a/common/src/main/java/io/netty/util/internal/Hidden.java b/common/src/main/java/io/netty/util/internal/Hidden.java index fec14d1254b..9094fd677f9 100644 --- a/common/src/main/java/io/netty/util/internal/Hidden.java +++ b/common/src/main/java/io/netty/util/internal/Hidden.java @@ -170,7 +170,9 @@ public Predicate<Thread> apply(final Predicate<Thread> p) { @Override @SuppressJava6Requirement(reason = "Predicate#test") public boolean test(Thread thread) { - return p.test(thread) || thread instanceof FastThreadLocalThread; + return p.test(thread) || + thread instanceof FastThreadLocalThread && + !((FastThreadLocalThread) thread).permitBlockingCalls(); } }; }
diff --git a/transport-blockhound-tests/src/test/java/io/netty/util/internal/NettyBlockHoundIntegrationTest.java b/transport-blockhound-tests/src/test/java/io/netty/util/internal/NettyBlockHoundIntegrationTest.java index 109543efe14..a005095d821 100644 --- a/transport-blockhound-tests/src/test/java/io/netty/util/internal/NettyBlockHoundIntegrationTest.java +++ b/transport-blockhound-tests/src/test/java/io/netty/util/internal/NettyBlockHoundIntegrationTest.java @@ -189,6 +189,23 @@ protected void run() { latch.await(); } + @Test + void permittingBlockingCallsInFastThreadLocalThreadSubclass() throws Exception { + final FutureTask<Void> future = new FutureTask<>(() -> { + Thread.sleep(0); + return null; + }); + FastThreadLocalThread thread = new FastThreadLocalThread(future) { + @Override + public boolean permitBlockingCalls() { + return true; // The Thread.sleep(0) call should not be flagged because we allow blocking calls. + } + }; + thread.start(); + future.get(5, TimeUnit.SECONDS); + thread.join(); + } + @Test @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS) public void testHashedWheelTimerStartStop() throws Exception {
test
test
"2022-11-03T14:18:53"
"2022-11-02T14:07:07Z"
jrhee17
val
netty/netty/12981_12988
netty/netty
netty/netty/12981
netty/netty/12988
[ "keyword_pr_to_issue" ]
76296425f4ee199de6dc3e3e03c40173cc5aa7de
ee9bb63aa5382bf9930eb0df4b690286173f126a
[ "I can contribute a fix for this." ]
[ "```suggestion\r\n // Check for dynamic table size updates, which must occur at the beginning:\r\n // https://www.rfc-editor.org/rfc/rfc7541.html#section-4.2\r\n decodeDynamicTableSizeUpdates(in);\r\n```", "```suggestion\r\n // See https://www.rfc-editor.org/rfc/rfc7541.html#section-4.2\r\n throw connectionError(COMPRESSION_ERROR, \"Dynamic table size update must happen \" +\r\n```", "can I commit this directly from github interface ?", "Yep... I just pressed the button for you :)", "thanks :-D" ]
"2022-11-11T09:32:53Z"
[]
HPACK dynamic table size update must happen at the beginning of the header block
### Expected behavior HPACK decoder accepts dynamic table size update at the beginning of the block. Cf RFC 7531, section 4.2 ### Actual behavior HPACK decoder tolerates dynamic table size update anywhere in the block `io.netty.handler.codec.http2.HpackDecoder` can be modified to only allow setDynamicTableSize to be called only if that is the first of the block processing and fail otherwise with a connection error like it does already. ### Steps to reproduce Send an HTTP/2 header frame with a dynamic table size update anywhere, e.g at the end of the stream ### Minimal yet complete reproducer code (or URL to code) N/A ### Netty version 4.1.84.Final ### JVM version (e.g. `java -version`) N/A ### OS version (e.g. `uname -a`) N/A
[ "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 ab5fe18d183..8fb6a2635ad 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 @@ -79,15 +79,14 @@ final class HpackDecoder { Http2Exception.newStatic(COMPRESSION_ERROR, "HPACK - max dynamic table size change required", Http2Exception.ShutdownHint.HARD_SHUTDOWN, HpackDecoder.class, "decode(..)"); private static final byte READ_HEADER_REPRESENTATION = 0; - private static final byte READ_MAX_DYNAMIC_TABLE_SIZE = 1; - private static final byte READ_INDEXED_HEADER = 2; - private static final byte READ_INDEXED_HEADER_NAME = 3; - private static final byte READ_LITERAL_HEADER_NAME_LENGTH_PREFIX = 4; - private static final byte READ_LITERAL_HEADER_NAME_LENGTH = 5; - private static final byte READ_LITERAL_HEADER_NAME = 6; - private static final byte READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX = 7; - private static final byte READ_LITERAL_HEADER_VALUE_LENGTH = 8; - private static final byte READ_LITERAL_HEADER_VALUE = 9; + private static final byte READ_INDEXED_HEADER = 1; + private static final byte READ_INDEXED_HEADER_NAME = 2; + private static final byte READ_LITERAL_HEADER_NAME_LENGTH_PREFIX = 3; + private static final byte READ_LITERAL_HEADER_NAME_LENGTH = 4; + private static final byte READ_LITERAL_HEADER_NAME = 5; + private static final byte READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX = 6; + private static final byte READ_LITERAL_HEADER_VALUE_LENGTH = 7; + private static final byte READ_LITERAL_HEADER_VALUE = 8; private final HpackHuffmanDecoder huffmanDecoder = new HpackHuffmanDecoder(); private final HpackDynamicTable hpackDynamicTable; @@ -127,6 +126,9 @@ final class HpackDecoder { void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception { Http2HeadersSink sink = new Http2HeadersSink( streamId, headers, maxHeaderListSize, validateHeaders); + // Check for dynamic table size updates, which must occur at the beginning: + // https://www.rfc-editor.org/rfc/rfc7541.html#section-4.2 + decodeDynamicTableSizeUpdates(in); decode(in, sink); // Now that we've read all of our headers we can perform the validation steps. We must @@ -134,6 +136,19 @@ void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHead sink.finish(); } + private void decodeDynamicTableSizeUpdates(ByteBuf in) throws Http2Exception { + byte b; + while (in.isReadable() && ((b = in.getByte(in.readerIndex())) & 0x20) == 0x20 && ((b & 0xC0) == 0x00)) { + in.readByte(); + int index = b & 0x1F; + if (index == 0x1F) { + setDynamicTableSize(decodeULE128(in, (long) index)); + } else { + setDynamicTableSize(index); + } + } + } + private void decode(ByteBuf in, Http2HeadersSink sink) throws Http2Exception { int index = 0; int nameLength = 0; @@ -184,13 +199,9 @@ private void decode(ByteBuf in, Http2HeadersSink sink) throws Http2Exception { } } else if ((b & 0x20) == 0x20) { // Dynamic Table Size Update - index = b & 0x1F; - if (index == 0x1F) { - state = READ_MAX_DYNAMIC_TABLE_SIZE; - } else { - setDynamicTableSize(index); - state = READ_HEADER_REPRESENTATION; - } + // See https://www.rfc-editor.org/rfc/rfc7541.html#section-4.2 + throw connectionError(COMPRESSION_ERROR, "Dynamic table size update must happen " + + "at the beginning of the header block"); } else { // Literal Header Field without Indexing / never Indexed indexType = (b & 0x10) == 0x10 ? IndexType.NEVER : IndexType.NONE; @@ -211,11 +222,6 @@ private void decode(ByteBuf in, Http2HeadersSink sink) throws Http2Exception { } break; - case READ_MAX_DYNAMIC_TABLE_SIZE: - setDynamicTableSize(decodeULE128(in, (long) index)); - state = READ_HEADER_REPRESENTATION; - break; - case READ_INDEXED_HEADER: HpackHeaderField indexedHeader = getIndexedHeader(decodeULE128(in, index)); sink.appendToHeaderList(
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 452f4179cee..e376197f12b 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 @@ -403,6 +403,22 @@ public void execute() throws Throwable { }); } + @Test + public void testDynamicTableSizeUpdateAfterTheBeginingOfTheBlock() throws Http2Exception { + assertThrows(Http2Exception.class, new Executable() { + @Override + public void execute() throws Throwable { + decode("8120"); + } + }); + assertThrows(Http2Exception.class, new Executable() { + @Override + public void execute() throws Throwable { + decode("813FE11F"); + } + }); + } + @Test public void testLiteralWithIncrementalIndexingWithEmptyName() throws Http2Exception { decode("400005" + hex("value"));
val
test
"2022-11-11T10:20:41"
"2022-11-09T15:22:23Z"
vietj
val
netty/netty/13003_13004
netty/netty
netty/netty/13003
netty/netty/13004
[ "keyword_pr_to_issue" ]
09ac33766f6c30d445dcdfb4285f589aedf5d7fe
6e935e073fe877a73ef55d5b2df0ba913d52de47
[ "@normanmaurer PTAL" ]
[ "I think this is not correct... this should still be optional otherwise we have it as non optional dependency for handler as well. \r\n\r\nSame its true for the other change in here. " ]
"2022-11-16T12:23:20Z"
[]
Release Handler-Ssl-Ocsp
Netty [Handler-Ssl-Ocsp](https://github.com/netty/netty/commit/09ac33766f6c30d445dcdfb4285f589aedf5d7fe) was merged but the module is not present in bom.xml. Hence, snapshots are not being deployed.
[ "all/pom.xml", "bom/pom.xml", "handler-ssl-ocsp/pom.xml" ]
[ "all/pom.xml", "bom/pom.xml", "handler-ssl-ocsp/pom.xml" ]
[]
diff --git a/all/pom.xml b/all/pom.xml index 9f22ed3b174..d19dd9e52d4 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -298,6 +298,11 @@ <artifactId>netty-handler-proxy</artifactId> <scope>compile</scope> </dependency> + <dependency> + <groupId>io.netty</groupId> + <artifactId>netty-handler-ssl-ocsp</artifactId> + <scope>compile</scope> + </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>netty-resolver</artifactId> diff --git a/bom/pom.xml b/bom/pom.xml index 5787d21e042..e0e89be4f7b 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -165,6 +165,11 @@ <artifactId>netty-handler-proxy</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>io.netty</groupId> + <artifactId>netty-handler-ssl-ocsp</artifactId> + <version>${project.version}</version> + </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-resolver</artifactId> diff --git a/handler-ssl-ocsp/pom.xml b/handler-ssl-ocsp/pom.xml index 9012d02a849..971749e026a 100644 --- a/handler-ssl-ocsp/pom.xml +++ b/handler-ssl-ocsp/pom.xml @@ -21,7 +21,7 @@ <parent> <groupId>io.netty</groupId> <artifactId>netty-parent</artifactId> - <version>4.1.85.Final-SNAPSHOT</version> + <version>4.1.86.Final-SNAPSHOT</version> </parent> <artifactId>netty-handler-ssl-ocsp</artifactId> @@ -37,6 +37,7 @@ <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> + <scope>provided</scope> </dependency> <dependency> <groupId>io.netty</groupId>
null
train
test
"2022-11-15T20:10:44"
"2022-11-16T12:08:43Z"
hyperxpro
val
netty/netty/13018_13021
netty/netty
netty/netty/13018
netty/netty/13021
[ "keyword_pr_to_issue" ]
3bff0bee692b5bcb67f8fe5f900d2e899a7fa1f8
b64a6e22b2f410d3092f4a2e9f8edcf8c51262b2
[ "@chrisvest I investigated the issue and didn't find a behavior change in HashedWheelTimer. I used HashedWheelTimerTest and made several variations of testExecutionOnTime. \r\n\r\nThere might be some subtle change that causes the issue, and we'll just have to deal with that in Pulsar.", "@lhotari After reading your comment, I reviewed my code and realised I made a mistake in #12888.\r\nMy optimisation based on the assumption that the tasks in a bucket are originally in the order of execution time, which are in fact not.\r\nSo breaking the loop at `execRound > currRound` may cause latter tasks not respond in time.", "Sorry for making that trouble. I already made a PR #13021 to revert it. @lhotari @chrisvest ", "> @lhotari After reading your comment, I reviewed my code and realised I made a mistake in #12888.\n> My optimisation based on the assumption that the tasks in a bucket are originally in the order of execution time, which are in fact not.\n> So breaking the loop at `execRound > currRound` may cause latter tasks not respond in time.\n\n@needmorecode Thanks for the quick confirmation and investigation. Your explanation makes sense. I missed that case when I was trying to add a unit test that would prove an issue." ]
[]
"2022-11-27T00:16:58Z"
[]
HashedWheelTimer task scheduling behavior changed in 4.1.85
### Expected behavior The expectation is that task scheduling behavior of HashedWheelTimer doesn't change significantly between Netty 4.1.x releases. ### Actual behavior The HashedWheelTimer behavior changed in some way that makes multiple integration tests to fail in Apache Pulsar. The only change in HashedWheelTimer in 4.1.85.Final is the PR #12888 . ### Steps to reproduce There are steps to reproduce by running a specific test in Apache Pulsar project. The instructions are in a PR in the Apache Pulsar repo: https://github.com/apache/pulsar/pull/18599#issuecomment-1327794984 ### Netty version 4.1.85.Final ### JVM version (e.g. `java -version`) ``` openjdk version "17.0.5" 2022-10-18 OpenJDK Runtime Environment Temurin-17.0.5+8 (build 17.0.5+8) OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (build 17.0.5+8, mixed mode, sharing) ``` ### OS version (e.g. `uname -a`) Linux x86_64
[ "common/src/main/java/io/netty/util/HashedWheelTimer.java" ]
[ "common/src/main/java/io/netty/util/HashedWheelTimer.java" ]
[]
diff --git a/common/src/main/java/io/netty/util/HashedWheelTimer.java b/common/src/main/java/io/netty/util/HashedWheelTimer.java index 126f9998104..8db3ea747e1 100644 --- a/common/src/main/java/io/netty/util/HashedWheelTimer.java +++ b/common/src/main/java/io/netty/util/HashedWheelTimer.java @@ -116,7 +116,6 @@ public class HashedWheelTimer implements Timer { private final AtomicLong pendingTimeouts = new AtomicLong(0); private final long maxPendingTimeouts; private final Executor taskExecutor; - private long currRound; private volatile long startTime; @@ -497,14 +496,11 @@ public void run() { final long deadline = waitForNextTick(); if (deadline > 0) { int idx = (int) (tick & mask); - if (idx == 0 && tick > 0) { - currRound ++; - } processCancelledTasks(); HashedWheelBucket bucket = wheel[idx]; transferTimeoutsToBuckets(); - bucket.expireTimeouts(deadline, currRound); + bucket.expireTimeouts(deadline); tick++; } } while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED); @@ -540,7 +536,7 @@ private void transferTimeoutsToBuckets() { } long calculated = timeout.deadline / tickDuration; - timeout.execRound = calculated / wheel.length; + timeout.remainingRounds = (calculated - tick) / wheel.length; final long ticks = Math.max(calculated, tick); // Ensure we don't schedule for past. int stopIndex = (int) (ticks & mask); @@ -630,9 +626,9 @@ private static final class HashedWheelTimeout implements Timeout, Runnable { @SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization" }) private volatile int state = ST_INIT; - // execRound will be calculated and set by Worker.transferTimeoutsToBuckets() before the + // remainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the // HashedWheelTimeout will be added to the correct HashedWheelBucket. - long execRound; + long remainingRounds; // This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list. // As only the workerThread will act on it there is no need for synchronization / volatile. @@ -782,13 +778,13 @@ public void addTimeout(HashedWheelTimeout timeout) { /** * Expire all {@link HashedWheelTimeout}s for the given {@code deadline}. */ - public void expireTimeouts(long deadline, long currRound) { + public void expireTimeouts(long deadline) { HashedWheelTimeout timeout = head; // process all timeouts while (timeout != null) { HashedWheelTimeout next = timeout.next; - if (timeout.execRound <= currRound) { + if (timeout.remainingRounds <= 0) { next = remove(timeout); if (timeout.deadline <= deadline) { timeout.expire(); @@ -800,7 +796,7 @@ public void expireTimeouts(long deadline, long currRound) { } else if (timeout.isCancelled()) { next = remove(timeout); } else { - break; + timeout.remainingRounds --; } timeout = next; }
null
test
test
"2022-11-24T14:34:25"
"2022-11-25T19:20:42Z"
lhotari
val
netty/netty/12000_13099
netty/netty
netty/netty/12000
netty/netty/13099
[ "keyword_pr_to_issue" ]
9541bc17e0c637ec77ccc3d6b67a19a0d024f925
52db529c9daf1017422e3c4a8810da09e66d14a6
[ "Related to https://github.com/spring-cloud/spring-cloud-gateway/issues/2493" ]
[ "I think we still need to ensure we only create a `SSLHandshakeException` if we are really still handshaking.\r\n```suggestion\r\n final Exception exception;\r\n if (handshakePromise.isDone()) {\r\n exception = new ClosedChannelException();\r\n } else {\r\n // Closed before the handshake was done.\r\n exception = new SSLHandshakeException(\"Connection closed during handshake\");\r\n exception.initCause(new ClosedChannelException()); \r\n }\r\n```", "There is a possibility that the channel will become inactive even before it was able to read anything and start the handshake. Consider `!isStateSet(STATE_HANDSHAKE_STARTED) || handshakePromise.isDone()` ", "It doesn't provide much value and produces too much logging output if we generate stack-trace twice from the same method. Consider making either `ClosedChannelException` or `SSLHandshakeException` stack-less in this case.", "In the previous round of feedback the logic was opposite. The above condition was for `ClosedChannelException`. Since now we changed the logic, we have to flip this condition as well. Consider: `isStateSet(STATE_HANDSHAKE_STARTED) && !handshakePromise.isDone()`.", "\"before\" doesn't help to understand if it was \"before handshake started\" or \"after it started but before it complete\". Consider clarifying that the handshake started, but didn't complete", "Since it's a subtype of `SSLHandshakeException` with the same meaning, consider making it pkg-private.", "Yeah, sorry. My bad. ;/", "```suggestion\r\n new StacklessSSLHandshakeException(\"Connection closed while SSL/TLS handshake was in progress\"));\r\n```" ]
"2023-01-05T19:39:01Z"
[]
exception when close channel before SSL
### Expected behavior close channel no exception ### Actual behavior 2022/01/13 17:56:07.897 [] [reactor-http-epoll-2] [WARN] i.n.h.s.ApplicationProtocolNegotiationHandler - [id: 0xa03cf599, L:/189.11.24.119:8443 ! R:/189.11.24.38:39277] Failed to select the application-level protocol: java.nio.channels.ClosedChannelException: null at io.netty.handler.ssl.SslHandler.channelInactive(SslHandler.java:1063) [netty-handler-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:241) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1405) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:262) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:248) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:901) [netty-transport-4.1.72.Final.jar!/:4.1.72.Final] at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:831) ### Steps to reproduce server is 189.11.24.119 8443 client is 189.11.24.38 The tcpdump packet capture result is as follows: ![image](https://user-images.githubusercontent.com/13596975/149335475-2972a124-bafa-482a-90f1-4cc94f4a8710.png) ### Minimal yet complete reproducer code (or URL to code) NA ### Netty version 4.1.72.Final ### JVM version (e.g. `java -version`) openjdk 11.0.8 ### OS version (e.g. `uname -a`) linux x86
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslHandler.java", "handler/src/main/java/io/netty/handler/ssl/StacklessSSLHandshakeException.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 d59b504c709..83ce18e747f 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java @@ -47,6 +47,7 @@ import io.netty.util.concurrent.PromiseNotifier; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.PlatformDependent; +import io.netty.util.internal.ThrowableUtil; import io.netty.util.internal.UnstableApi; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; @@ -1062,7 +1063,15 @@ private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf i public void channelInactive(ChannelHandlerContext ctx) throws Exception { boolean handshakeFailed = handshakePromise.cause() != null; + // Channel closed, we will generate 'ClosedChannelException' now. ClosedChannelException exception = new ClosedChannelException(); + + // Add a supressed exception if the handshake was not completed yet. + if (isStateSet(STATE_HANDSHAKE_STARTED) && !handshakePromise.isDone()) { + ThrowableUtil.addSuppressed(exception, + new StacklessSSLHandshakeException("Connection closed while SSL/TLS handshake was in progress")); + } + // Make sure to release SSLEngine, // and notify the handshake future if the connection has been closed during handshake. setHandshakeFailure(ctx, exception, !isStateSet(STATE_OUTBOUND_CLOSED), isStateSet(STATE_HANDSHAKE_STARTED), diff --git a/handler/src/main/java/io/netty/handler/ssl/StacklessSSLHandshakeException.java b/handler/src/main/java/io/netty/handler/ssl/StacklessSSLHandshakeException.java new file mode 100644 index 00000000000..3c315892fea --- /dev/null +++ b/handler/src/main/java/io/netty/handler/ssl/StacklessSSLHandshakeException.java @@ -0,0 +1,43 @@ +/* + * Copyright 2023 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: + * + * https://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.SSLHandshakeException; + +/** + * A {@link SSLHandshakeException} that does not fill in the stack trace. + */ +final class StacklessSSLHandshakeException extends SSLHandshakeException { + + private static final long serialVersionUID = -1244781947804415549L; + + /** + * Constructs an exception reporting an error found by + * an SSL subsystem during handshaking. + * + * @param reason describes the problem. + */ + StacklessSSLHandshakeException(String reason) { + super(reason); + } + + @Override + public Throwable fillInStackTrace() { + // This is a performance optimization to not fill in the + // stack trace as this is a stackless exception. + return this; + } +}
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 70aef23b602..bd8e0ac79e5 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslHandlerTest.java @@ -568,8 +568,8 @@ public void testCloseFutureNotified() throws Exception { assertFalse(ch.finishAndReleaseAll()); - assertTrue(handler.handshakeFuture().cause() instanceof ClosedChannelException); - assertTrue(handler.sslCloseFuture().cause() instanceof ClosedChannelException); + assertThat(handler.handshakeFuture().cause(), instanceOf(ClosedChannelException.class)); + assertThat(handler.sslCloseFuture().cause(), instanceOf(ClosedChannelException.class)); } @Test @@ -590,11 +590,11 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc SslCompletionEvent evt = events.take(); assertTrue(evt instanceof SslHandshakeCompletionEvent); - assertTrue(evt.cause() instanceof ClosedChannelException); + assertThat(evt.cause(), instanceOf(ClosedChannelException.class)); evt = events.take(); assertTrue(evt instanceof SslCloseCompletionEvent); - assertTrue(evt.cause() instanceof ClosedChannelException); + assertThat(evt.cause(), instanceOf(ClosedChannelException.class)); assertTrue(events.isEmpty()); }
train
test
"2023-01-23T11:06:24"
"2022-01-13T13:06:59Z"
xingzhang8023
val
netty/netty/10616_13158
netty/netty
netty/netty/10616
netty/netty/13158
[ "keyword_pr_to_issue" ]
315c738b6f2b4a0d69e5e4e6f6188fb6774878bc
79b347234af27f34344fecc2b5651295f3cd3e7c
[ "Can you add instructions for building and running your repro?", "Sorry yes, updated comment.", "@perezd How do you make the repro use a Netty version that's built and installed into the local `~/.m2/` repository? I'm trying to make it use a local `4.1.53.Final-SNAPSHOT` version, but just changing the `NETTY_VERSION` constant in the `WORKSPACE` file is not enough.", "This would work, if you add the jars to the BUILD file:\r\nhttps://docs.bazel.build/versions/master/be/java.html#java_import\r\n\r\nThen just changes `deps` to point to that new target and it should work.", "I think this was fixed ?", "/cc @chrisvest ", "I get the following error, which I don't understand, when I run the reproducer build with a 4.1.54.Final-SNAPSHOT version of Netty:\r\n\r\n```\r\n[chris@localhost netty-epoll-native-repro]$ bazel run :main-native --sandbox_debug\r\nINFO: Analyzed target //:main-native (1 packages loaded, 11 targets configured).\r\nINFO: Found 1 target...\r\nINFO: From Extracting interface //third_party:netty:\r\n1603979213.739407504: src/main/tools/linux-sandbox.cc:152: calling pipe(2)...\r\n1603979213.739430730: src/main/tools/linux-sandbox.cc:171: calling clone(2)...\r\n1603979213.739633277: src/main/tools/linux-sandbox.cc:180: linux-sandbox-pid1 has PID 30613\r\n1603979213.739668113: src/main/tools/linux-sandbox-pid1.cc:434: Pid1Main started\r\n1603979213.739768241: src/main/tools/linux-sandbox.cc:197: done manipulating pipes\r\n1603979213.739791637: src/main/tools/linux-sandbox-pid1.cc:176: working dir: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/48/execroot/grl\r\n1603979213.739807831: src/main/tools/linux-sandbox-pid1.cc:208: writable: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/48/execroot/grl\r\n1603979213.739815223: src/main/tools/linux-sandbox-pid1.cc:208: writable: /tmp\r\n1603979213.739820767: src/main/tools/linux-sandbox-pid1.cc:208: writable: /dev/shm\r\n1603979213.739867607: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /\r\n1603979213.739877071: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys\r\n1603979213.739882570: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/security\r\n1603979213.739889160: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/cgroup\r\n1603979213.739894040: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/pstore\r\n1603979213.739899400: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/bpf\r\n1603979213.739904071: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/config\r\n1603979213.739908633: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/selinux\r\n1603979213.739913332: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/tracing\r\n1603979213.739917879: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/debug\r\n1603979213.739922570: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/fuse/connections\r\n1603979213.739928426: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev\r\n1603979213.739932441: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /dev/shm\r\n1603979213.739954786: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/pts\r\n1603979213.739960071: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/mqueue\r\n1603979213.739963898: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/hugepages\r\n1603979213.739967826: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run\r\n1603979213.739972297: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/vmblock-fuse\r\n1603979213.739976810: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/user/1000\r\n1603979213.739981507: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/user/1000/gvfs\r\n1603979213.739985922: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /proc\r\n1603979213.739990035: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /proc/sys/fs/binfmt_misc\r\n1603979213.739996764: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /tmp\r\n1603979213.740000021: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /boot\r\n1603979213.740003624: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /var/lib/nfs/rpc_pipefs\r\n1603979213.740010159: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /mnt/hgfs\r\n1603979213.740017960: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/48/execroot/grl\r\n1603979213.740022873: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/48/execroot/grl\r\n1603979213.740026346: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /tmp\r\n1603979213.740029038: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /dev/shm\r\n1603979213.740089170: src/main/tools/linux-sandbox-pid1.cc:363: calling fork...\r\n1603979213.740196745: src/main/tools/linux-sandbox-pid1.cc:393: child started with PID 2\r\n1603979213.757556894: src/main/tools/linux-sandbox-pid1.cc:410: wait returned pid=2, status=0x00\r\n1603979213.757569016: src/main/tools/linux-sandbox-pid1.cc:428: child exited normally with code 0\r\n1603979213.757889995: src/main/tools/linux-sandbox.cc:233: child exited normally with code 0\r\nERROR: /home/chris/netty-epoll-native-repro/BUILD:19:13: Action main-native-bin failed (Exit 1): linux-sandbox failed: error executing command \r\n (cd /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl && \\\r\n exec env - \\\r\n PATH=/usr/bin:/bin \\\r\n TMPDIR=/tmp \\\r\n /home/chris/.cache/bazel/_bazel_chris/install/792f43108e6f3e1e71623e5a11a5a382/linux-sandbox -t 15 -w /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl -w /tmp -w /dev/shm -D -- external/graal/bin/native-image --no-server --no-fallback -cp bazel-out/k8-fastbuild/bin/libmain.jar:third_party/netty/netty-common-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-buffer-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-codec-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-codec-http-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-native-unix-common-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-native-epoll-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-handler-4.1.54.Final-SNAPSHOT.jar '-H:Class=Main' '-H:Name=bazel-out/k8-fastbuild/bin/main-native-bin' '-H:CCompilerPath=/usr/bin/gcc' -H:+ReportExceptionStackTraces -H:+TraceClassInitialization --static) linux-sandbox failed: error executing command \r\n (cd /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl && \\\r\n exec env - \\\r\n PATH=/usr/bin:/bin \\\r\n TMPDIR=/tmp \\\r\n /home/chris/.cache/bazel/_bazel_chris/install/792f43108e6f3e1e71623e5a11a5a382/linux-sandbox -t 15 -w /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl -w /tmp -w /dev/shm -D -- external/graal/bin/native-image --no-server --no-fallback -cp bazel-out/k8-fastbuild/bin/libmain.jar:third_party/netty/netty-common-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-buffer-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-codec-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-codec-http-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-native-unix-common-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-transport-native-epoll-4.1.54.Final-SNAPSHOT.jar:third_party/netty/netty-handler-4.1.54.Final-SNAPSHOT.jar '-H:Class=Main' '-H:Name=bazel-out/k8-fastbuild/bin/main-native-bin' '-H:CCompilerPath=/usr/bin/gcc' -H:+ReportExceptionStackTraces -H:+TraceClassInitialization --static)\r\n1603979213.837758895: src/main/tools/linux-sandbox.cc:152: calling pipe(2)...\r\n1603979213.837780965: src/main/tools/linux-sandbox.cc:171: calling clone(2)...\r\n1603979213.837993852: src/main/tools/linux-sandbox.cc:180: linux-sandbox-pid1 has PID 30618\r\n1603979213.838038905: src/main/tools/linux-sandbox-pid1.cc:434: Pid1Main started\r\n1603979213.838124208: src/main/tools/linux-sandbox.cc:197: done manipulating pipes\r\n1603979213.838170860: src/main/tools/linux-sandbox-pid1.cc:176: working dir: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl\r\n1603979213.838188901: src/main/tools/linux-sandbox-pid1.cc:208: writable: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl\r\n1603979213.838195746: src/main/tools/linux-sandbox-pid1.cc:208: writable: /tmp\r\n1603979213.838201268: src/main/tools/linux-sandbox-pid1.cc:208: writable: /dev/shm\r\n1603979213.838264214: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /\r\n1603979213.838274941: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys\r\n1603979213.838280548: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/security\r\n1603979213.838287149: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/cgroup\r\n1603979213.838292243: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/pstore\r\n1603979213.838297864: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/bpf\r\n1603979213.838302218: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/config\r\n1603979213.838306876: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/selinux\r\n1603979213.838311431: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/tracing\r\n1603979213.838315842: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/kernel/debug\r\n1603979213.838320456: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /sys/fs/fuse/connections\r\n1603979213.838326254: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev\r\n1603979213.838330415: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /dev/shm\r\n1603979213.838353771: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/pts\r\n1603979213.838358470: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/mqueue\r\n1603979213.838362393: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /dev/hugepages\r\n1603979213.838366317: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run\r\n1603979213.838370249: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/vmblock-fuse\r\n1603979213.838374337: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/user/1000\r\n1603979213.838378989: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /run/user/1000/gvfs\r\n1603979213.838383515: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /proc\r\n1603979213.838387608: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /proc/sys/fs/binfmt_misc\r\n1603979213.838394500: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /tmp\r\n1603979213.838397649: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /boot\r\n1603979213.838401352: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /var/lib/nfs/rpc_pipefs\r\n1603979213.838407632: src/main/tools/linux-sandbox-pid1.cc:278: remount ro: /mnt/hgfs\r\n1603979213.838414908: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl\r\n1603979213.838419872: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /home/chris/.cache/bazel/_bazel_chris/79c5fdc3f25858db1b7fbca7ad47271b/sandbox/linux-sandbox/50/execroot/grl\r\n1603979213.838423186: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /tmp\r\n1603979213.838425830: src/main/tools/linux-sandbox-pid1.cc:278: remount rw: /dev/shm\r\n1603979213.838471119: src/main/tools/linux-sandbox-pid1.cc:363: calling fork...\r\n1603979213.838560767: src/main/tools/linux-sandbox-pid1.cc:393: child started with PID 2\r\nFatal error: com.oracle.graal.pointsto.util.AnalysisError$ParsingError: Error encountered while parsing com.oracle.svm.reflect.ClassLoader_defineClass_c6c343b4d6dc22ca64eb2d8503b13ac9c340dcb3.invoke(java.lang.Object, java.lang.Object[]) \r\nParsing context:\r\n\tparsing java.lang.reflect.Method.invoke(Method.java:566)\r\n\tparsing io.netty.util.internal.CleanerJava9.freeDirectBuffer(CleanerJava9.java:88)\r\n\tparsing io.netty.util.internal.PlatformDependent.freeDirectBuffer(PlatformDependent.java:483)\r\n\tparsing io.netty.channel.unix.Buffer.free(Buffer.java:33)\r\n\tparsing io.netty.channel.epoll.EpollEventArray.free(EpollEventArray.java:92)\r\n\tparsing io.netty.channel.epoll.EpollEventLoop.cleanup(EpollEventLoop.java:552)\r\n\tparsing io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:1036)\r\n\tparsing com.oracle.svm.core.jdk.RuntimeSupport.executeHooks(RuntimeSupport.java:144)\r\n\tparsing com.oracle.svm.core.jdk.RuntimeSupport.executeTearDownHooks(RuntimeSupport.java:121)\r\n\tparsing com.oracle.svm.core.graal.snippets.CEntryPointSnippets.tearDownIsolate(CEntryPointSnippets.java:361)\r\n\r\n\tat com.oracle.graal.pointsto.util.AnalysisError.parsingError(AnalysisError.java:138)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlow.doParse(MethodTypeFlow.java:327)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlow.ensureParsed(MethodTypeFlow.java:300)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlow.addContext(MethodTypeFlow.java:107)\r\n\tat com.oracle.graal.pointsto.DefaultAnalysisPolicy$DefaultVirtualInvokeTypeFlow.onObservedUpdate(DefaultAnalysisPolicy.java:191)\r\n\tat com.oracle.graal.pointsto.flow.TypeFlow.notifyObservers(TypeFlow.java:343)\r\n\tat com.oracle.graal.pointsto.flow.TypeFlow.update(TypeFlow.java:385)\r\n\tat com.oracle.graal.pointsto.BigBang$2.run(BigBang.java:511)\r\n\tat com.oracle.graal.pointsto.util.CompletionExecutor.lambda$execute$0(CompletionExecutor.java:171)\r\n\tat java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)\r\n\tat java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)\r\n\tat java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)\r\n\tat java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)\r\n\tat java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)\r\n\tat java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)\r\nCaused by: com.oracle.svm.hosted.substitute.DeletedElementException: Unsupported method java.lang.ClassLoader.defineClass(String, byte[], int, int) is reachable: The declaring class of this element has been substituted, but this element is not present in the substitution class\r\nTo diagnose the issue, you can add the option --report-unsupported-elements-at-runtime. The unsupported element is then reported at run time when it is accessed the first time.\r\n\tat com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.lookup(AnnotationSubstitutionProcessor.java:183)\r\n\tat com.oracle.graal.pointsto.infrastructure.SubstitutionProcessor$ChainedSubstitutionProcessor.lookup(SubstitutionProcessor.java:128)\r\n\tat com.oracle.graal.pointsto.infrastructure.SubstitutionProcessor$ChainedSubstitutionProcessor.lookup(SubstitutionProcessor.java:128)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisUniverse.lookupAllowUnresolved(AnalysisUniverse.java:397)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisUniverse.lookup(AnalysisUniverse.java:377)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisUniverse.lookup(AnalysisUniverse.java:75)\r\n\tat com.oracle.graal.pointsto.infrastructure.UniverseMetaAccess.lookupJavaMethod(UniverseMetaAccess.java:93)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisMetaAccess.lookupJavaMethod(AnalysisMetaAccess.java:66)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisMetaAccess.lookupJavaMethod(AnalysisMetaAccess.java:39)\r\n\tat com.oracle.svm.reflect.hosted.ReflectionSubstitutionType$ReflectiveInvokeMethod.buildGraph(ReflectionSubstitutionType.java:511)\r\n\tat com.oracle.graal.pointsto.meta.AnalysisMethod.buildGraph(AnalysisMethod.java:319)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.parse(MethodTypeFlowBuilder.java:185)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlowBuilder.apply(MethodTypeFlowBuilder.java:340)\r\n\tat com.oracle.graal.pointsto.flow.MethodTypeFlow.doParse(MethodTypeFlow.java:310)\r\n\t... 13 more\r\nError: Image build request failed with exit status 1\r\n1603979228.378204816: src/main/tools/linux-sandbox-pid1.cc:410: wait returned pid=2, status=0x100\r\n1603979228.378218295: src/main/tools/linux-sandbox-pid1.cc:428: child exited normally with code 1\r\n1603979228.378818653: src/main/tools/linux-sandbox.cc:233: child exited normally with code 1\r\n[bazel-out/k8-fastbuild/bin/main-native-bin:21] classlist: 2,611.26 ms\r\n[bazel-out/k8-fastbuild/bin/main-native-bin:21] (cap): 589.29 ms\r\n[bazel-out/k8-fastbuild/bin/main-native-bin:21] setup: 1,557.43 ms\r\n[bazel-out/k8-fastbuild/bin/main-native-bin:21] analysis: 9,680.26 ms\r\nTarget //:main-native failed to build\r\nUse --verbose_failures to see the command lines of failed build steps.\r\nINFO: Elapsed time: 14.778s, Critical Path: 14.64s\r\nINFO: 6 processes: 4 internal, 1 linux-sandbox, 1 worker.\r\nFAILED: Build did NOT complete successfully\r\nFAILED: Build did NOT complete successfully\r\n[chris@localhost netty-epoll-native-repro]$ \r\n```\r\n\r\nThese are the changes I made to the reproducer repo in order to get it sort-of building with custom jar files:\r\n\r\n```patch\r\ndiff --git a/BUILD b/BUILD\r\nindex 1c8f0c3..c953f9b 100644\r\n--- a/BUILD\r\n+++ b/BUILD\r\n@@ -5,10 +5,11 @@ java_library(\r\n name = \"main\",\r\n srcs = [\"Main.java\"],\r\n deps = [\r\n- \"@maven//:io_netty_netty_codec_http\",\r\n- \"@maven//:io_netty_netty_transport\",\r\n- \"@maven//:io_netty_netty_transport_native_epoll_linux_x86_64\",\r\n- \"@maven//:io_netty_netty_handler\",\r\n+ \t\"//third_party:netty\"\r\n+ #\"@maven//:io_netty_netty_codec_http\",\r\n+ #\"@maven//:io_netty_netty_transport\",\r\n+ #\"@maven//:io_netty_netty_transport_native_epoll_linux_x86_64\",\r\n+ #\"@maven//:io_netty_netty_handler\",\r\n ],\r\n )\r\n \r\ndiff --git a/WORKSPACE b/WORKSPACE\r\nindex 1beffb0..e0cb416 100644\r\n--- a/WORKSPACE\r\n+++ b/WORKSPACE\r\n@@ -4,8 +4,8 @@ load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\r\n \r\n http_archive(\r\n name = \"rules_graal\",\r\n- sha256 = \"c1445dd6263b17b110da69178c238dc0925bbea1bffc93c46f5af4f8027245cc\",\r\n- strip_prefix = \"rules_graal-master\",\r\n+ sha256 = \"f5fc694e0abe24699987aab1c4054536c1792ed8a17123a9d7223511fac2367d\",\r\n+ strip_prefix = \"rules_graal-1b5f6deef8352c4b64541bb0f699fd2af5ae6b0b\",\r\n urls = [\r\n \"https://github.com/andyscott/rules_graal/archive/1b5f6deef8352c4b64541bb0f699fd2af5ae6b0b.zip\",\r\n ],\r\n@@ -72,3 +72,4 @@ maven_install(\r\n load(\"@maven//:defs.bzl\", \"pinned_maven_install\")\r\n \r\n pinned_maven_install()\r\n+\r\ndiff --git a/third_party/BUILD b/third_party/BUILD\r\nnew file mode 100644\r\nindex 0000000..aa16a03\r\n--- /dev/null\r\n+++ b/third_party/BUILD\r\n@@ -0,0 +1,14 @@\r\n+package(default_visibility = [\"//visibility:public\"])\r\n+java_import(\r\n+\tname = \"netty\",\r\n+\tjars = [\r\n+\t \"netty/netty-common-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-buffer-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-codec-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-codec-http-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-transport-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-transport-native-unix-common-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-transport-native-epoll-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t \"netty/netty-handler-4.1.54.Final-SNAPSHOT.jar\",\r\n+\t],\r\n+)\r\n```", "The Epoll transport is currently not supported in Graal because it loads classes from JNI code, and those classes needs to be initialised at runtime.\r\n\r\nYou can work around this by adding something like this to the `native-image` command:\r\n\r\n```\r\n--initialize-at-run-time=io.netty.handler.ssl.util.ThreadLocalInsecureRandom,io.netty.channel.unix,io.netty.channel.epoll,io.netty.channel.kqueue\r\n```", "@perezd I tried making epoll work in Graal native-image in #11163, but it's running into issues I don't fully understand. If you have any ideas feel free to chime in.", "Bit out if my depths here but wondering if it could have to do with JNI config? https://www.graalvm.org/reference-manual/native-image/JNI/\r\n\r\nDoes netty use reflection related to JNI? This could cause an issue potentially?", "@chrisvest So where does this stand now that https://github.com/netty/netty/pull/11163 has been closed?", "@ScottPierce You will have to use NIO transport with native-image for the foreseeable future. ", "What if we don't have the ability to choose? The library we use just pulls this stuff in.", "@ScottPierce we are happy to review a PR but we clearly not have the needed knowledge to fix this ourselves. Sorry ", "I wasn't being snarky. I was more asking if I can exclude dependencies and the pull in the right one and have a reasonable expectation of it still working. Thanks! ", "@ScottPierce I guess that is more the question for the library that pulls in netty :)", "Hello, I try to build a native image of a **Micronaut** service and have lots of similar errors \r\n\r\n> (Error: Classes that should be initialized at run time got initialized during image building:\r\n> io.grpc.netty.shaded.io.netty.buffer.ByteBufUtil the class was requested to be initialized at run time (from jar:file:///home/jacek/.gradle/caches/modules-2/files-2.1/io.grpc/grpc-netty-shaded/1.41.0/43fee785c101b3bfa3f7d916d8b47d5d736cbff2/grpc-netty-shaded-1.41.0.jar!/META-INF/native-image/io.grpc.netty.shaded.io.netty/buffer/native-image.properties with 'io.grpc.netty.shaded.io.netty.buffer.ByteBufUtil'). To see why io.grpc.netty.shaded.io.netty.buffer.ByteBufUtil got initialized use --trace-class-initialization=io.grpc.netty.shaded.io.netty.buffer.ByteBufUtil\r\n> io.grpc.netty.shaded.io.netty.buffer.ByteBufAllocator the class was requested to be initialized at run time (from jar:file:///home/jacek/.gradle/caches/modules-2/files-2.1/io.grpc/grpc-netty-shaded/1.41.0/43fee785c101b3bfa3f7d916d8b47d5d736cbff2/grpc-netty-shaded-1.41.0.jar!/META-INF/native-image/io.grpc.netty.shaded.io.netty/buffer/native-image.properties with 'io.grpc.netty.shaded.io.netty.buffer.ByteBufAllocator'). To see why io.grpc.netty.shaded.io.netty.buffer.ByteBufAllocator got initialized use --trace-class-initialization=io.grpc.netty.shaded.io.netty.buffer.ByteBufAllocator\r\n> .............\r\n\r\nIs there a known solution or a workaround for this?\r\nFrom various suggestions I tried\r\n```\r\n buildArgs.add(\r\n \"--initialize-at-run-time=\" +\r\n \"io.grpc.netty.shaded.io.netty.util.internal.logging.Log4JLogger,\" +\r\n \"io.grpc.netty.shaded.io.netty.handler.ssl.JdkNpnApplicationProtocolNegotiator,\" +\r\n \"io.netty.handler.ssl.util.ThreadLocalInsecureRandom,\" +\r\n \"io.netty.channel.unix,io.netty.channel.epoll,io.netty.channel.kqueue\"\r\n)\r\n```\r\nbut it didn't help.\r\nIs there some radical workaround which maybe sacrifice performance but at least allow to successfully compile?", "I also ran into this again with Netty 4.1.70 and GraalVM 21.3.0 but was able to get it working with:\r\n```\r\n --initialize-at-run-time=io.netty.channel.DefaultFileRegion\r\n --initialize-at-run-time=io.netty.channel.epoll.Native\r\n --initialize-at-run-time=io.netty.channel.epoll.Epoll\r\n --initialize-at-run-time=io.netty.channel.epoll.EpollEventLoop\r\n --initialize-at-run-time=io.netty.channel.epoll.EpollEventArray\r\n --initialize-at-run-time=io.netty.channel.kqueue.KQueue\r\n --initialize-at-run-time=io.netty.channel.kqueue.KQueueEventLoop\r\n --initialize-at-run-time=io.netty.channel.kqueue.KQueueEventArray\r\n --initialize-at-run-time=io.netty.channel.kqueue.Native\r\n --initialize-at-run-time=io.netty.channel.unix.Limits\r\n --initialize-at-run-time=io.netty.channel.unix.Errors\r\n --initialize-at-run-time=io.netty.channel.unix.IovArray\r\n```", "I tinkered a bit with epoll and GraalVM 23.0 - I managed to build the original sample project, but I couldn't figure out how to tweak Bazel to use a newer GraalVM version - I've created the following sample repository that uses Gradle: https://github.com/gradinac/netty-epoll-native-image. This project uses the original reproducer from @perezd, but uses Gradle as the build system\r\n\r\nI've hit two different categories of issues:\r\n 1. Class initialization problems - Netty 4.1 is by default fully initialized at image build time. However, epoll classes require native code and shouldn't be initialized at image build time. On top of that, these classes also use other classes in their static initializer that shouldn't be used during the image build (example: `io.netty.util.AbstractReferenceCounted`). Thank you @jamesward for the above list! :) It works without any modifications, but I've modified it a little bit in the repo. A sidenote: for Gradle and Maven projects, users can also add the [Native Build Tools](https://github.com/graalvm/native-build-tools) to their project and enable the metadata repository. Netty 4.1 metadata in this repository will automatically disable build-time initialization of Netty\r\n 2. Missing metadata - it appears we are missing some metadata for epoll, especially for JNI. Netty also appears to have many ways to fetch the native transport library, out of which one is to fetch it as a Java resource and extract it under `/tmp` at runtime. That approach seems to work fine, so I've also added a `resource-config.json` that includes this library if epoll is used.\r\n\r\nIf it's okay, I'll create a PR that adds the flags and the metadata to Netty 4.1\r\n\r\n" ]
[]
"2023-01-26T18:53:30Z"
[ "graal" ]
native-image compilation of epoll transport fails
### Expected behavior My small repro compiles as a native image and works as expected if I use Nio* family of transports. My expectation was that switching to epoll transport would similarly work. ### Actual behavior If I switch to epoll (linux-x86_64) I get a compilation error: ``` Error: Classes that should be initialized at run time got initialized during image building: io.netty.util.AbstractReferenceCounted the class was requested to be initialized at build time (from the command line). io.netty.util.AbstractReferenceCounted has been initialized without the native-image initialization instrumentation and the stack trace can't be tracked. Try avoiding to initialize the class that caused initialization of io.netty.util.AbstractReferenceCounted com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building: io.netty.util.AbstractReferenceCounted the class was requested to be initialized at build time (from the command line). io.netty.util.AbstractReferenceCounted has been initialized without the native-image initialization instrumentation and the stack trace can't be tracked. Try avoiding to initialize the class that caused initialization of io.netty.util.AbstractReferenceCounted at com.oracle.svm.core.util.UserError.abort(UserError.java:65) at com.oracle.svm.hosted.classinitialization.ConfigurableClassInitialization.checkDelayedInitialization(ConfigurableClassInitialization.java:510) at com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:187) at com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$8(NativeImageGenerator.java:710) at com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:63) at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:710) at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:530) at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:445) at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1407) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177) ``` ### Minimal yet complete reproducer code (or URL to code) Here's a repro: https://github.com/perezd/netty-epoll-native-repro w/ Bazel 3.5.0 installed, run this command from the root of the project: ``` bazel run :main-native ``` ### Netty version 4.1.52.Final (linux-x86_64) ### JVM version (e.g. `java -version`) java -version openjdk version "11.0.8" 2020-07-14 OpenJDK Runtime Environment (build 11.0.8+10-post-Ubuntu-0ubuntu120.04) OpenJDK 64-Bit Server VM (build 11.0.8+10-post-Ubuntu-0ubuntu120.04, mixed mode, sharing) ### OS version (e.g. `uname -a`) Linux desktop 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux I've searched around and attempted various workarounds but nothing seems to work.
[]
[ "transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/jni-config.json", "transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/native-image.properties", "transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/reflect-config.json", "transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/resource-config.json" ]
[]
diff --git a/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/jni-config.json b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/jni-config.json new file mode 100644 index 00000000000..493b2ed220a --- /dev/null +++ b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/jni-config.json @@ -0,0 +1,170 @@ +[ + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.ChannelException" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.DefaultFileRegion", + "allDeclaredFields": true + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.epoll.LinuxSocket" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.epoll.Native" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.epoll.NativeDatagramPacketArray$NativeDatagramPacket", + "allDeclaredFields": true + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.epoll.NativeStaticallyReferencedJniMethods" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.Buffer" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.DatagramSocketAddress", + "methods":[{"name":"<init>","parameterTypes":["byte[]","int","int","int","io.netty.channel.unix.DatagramSocketAddress"] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.DomainDatagramSocketAddress", + "methods":[{"name":"<init>","parameterTypes":["byte[]","int","io.netty.channel.unix.DomainDatagramSocketAddress"] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.ErrorsStaticallyReferencedJniMethods" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.FileDescriptor" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.LimitsStaticallyReferencedJniMethods" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.PeerCredentials", + "methods":[{"name":"<init>","parameterTypes":["int","int","int[]"] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.unix.Socket" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.io.FileDescriptor", + "fields":[{"name":"fd"}] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.io.IOException" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.lang.Boolean", + "methods":[{"name":"getBoolean","parameterTypes":["java.lang.String"] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.lang.OutOfMemoryError" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.lang.RuntimeException" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.net.InetSocketAddress", + "methods":[{"name":"<init>","parameterTypes":["java.lang.String","int"] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.net.PortUnreachableException" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.nio.Buffer", + "fields":[ + {"name":"limit"}, + {"name":"position"} + ], + "methods":[ + {"name":"limit","parameterTypes":[] }, + {"name":"position","parameterTypes":[] } + ] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.nio.DirectByteBuffer" + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"java.nio.channels.ClosedChannelException", + "methods":[{"name":"<init>","parameterTypes":[] }] + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"sun.nio.ch.FileChannelImpl", + "fields":[{"name":"fd"}] + } +] diff --git a/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/native-image.properties b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/native-image.properties new file mode 100644 index 00000000000..ff444c869bf --- /dev/null +++ b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/native-image.properties @@ -0,0 +1,15 @@ +# Copyright 2023 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: +# +# https://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. + +Args = --initialize-at-run-time=io.netty.channel.epoll,io.netty.channel.unix.Limits,io.netty.channel.unix.IovArray,io.netty.channel.unix.Errors diff --git a/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/reflect-config.json b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/reflect-config.json new file mode 100644 index 00000000000..74aa081bc99 --- /dev/null +++ b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/reflect-config.json @@ -0,0 +1,16 @@ +[ + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name":"io.netty.channel.epoll.EpollServerSocketChannel", + "allDeclaredConstructors": true + }, + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "name": "io.netty.util.internal.NativeLibraryUtil", + "allDeclaredMethods": true + } +] diff --git a/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/resource-config.json b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/resource-config.json new file mode 100644 index 00000000000..4998b6e6039 --- /dev/null +++ b/transport-classes-epoll/src/main/resources/META-INF/native-image/io.netty/netty-transport-classes-epoll/resource-config.json @@ -0,0 +1,13 @@ +{ + "resources":{ + "includes":[ + { + "condition": { + "typeReachable": "io.netty.channel.epoll.Native" + }, + "pattern":".*libnetty_transport_native_epoll_.*\\.so" + } + ]}, + "bundles":[] +} +
null
val
test
"2023-01-26T12:13:27"
"2020-09-28T00:33:12Z"
perezd
val
netty/netty/13208_13209
netty/netty
netty/netty/13208
netty/netty/13209
[ "keyword_pr_to_issue" ]
cfcdd93db5fd9af6254144caad68f4ed29a3dc64
1cfe7103fbf7acdc5e21365419e9565955540703
[ "When can this be released ?", "I think in the next 2-3 weeks. " ]
[ "API Breakage", "API Breakage", "API Breakage", "API Breakage", "API Breakage", "API Breakage", "API Breakage", "I know there is API breakage, but I was wondering if we can still afford it given that this interface is pretty recent.", "No, we can't break applications.", "Hmm, then I need to figure out another way to add this debug information. BTW the original change of adding the validation itself is a breaking change. ", "No, it isn't. The public API was preserved.", "The public API is preserved but the actual runtime behavior was changed. Prior to the validation change the header values were leniently accepted but now there is a stricter validation, which IMO is a good thing but it broke one of our applications which was adding an empty space in a header.\r\n\r\nNow an error is thrown but it isn't clear which header is the one which has a whitespace.", "I agree the runtime behaviour changed but I still think it was an \"acceptable\" change due the security impact of not doing so", "I didn't look to closely but maybe what could be done is to \"catch and rethrow\" when this happens. The caller would then add the extra details ", "@normanmaurer That was what I initially thought of doing, but it seemed hacky. I have another approach of creating another interface which is also API compatible. I will update the PR, if you like it that's fine. Otherwise will fallback to catch, change message and rethrow.", " ~~@normanmaurer This is what I am thinking of doing,~~\r\n\r\n~~1. Create a new interface `HeaderValueValidator<K, V>`, the benefit of this interface would be if we want to do a contextual validations of headers on the basis of what the header represents it would be possible via this interface. I feel validation of header values without having context of their name works now but seems inflexible to me.~~\r\n~~2. Mark `ValueValidator` as deprecated but still keep it around because we can't break public APIs. During actual validation we check which of `HeaderValueValidator` or `ValueValidator` has been provided and based on that call the appropriate validator. If a user is currently extending `DefaultHeaders` their implementations would still pass `ValueValidator` and continue to function as is, new users would pass a `HeaderValueValidator`.~~\r\n\r\n~~I could have made `HeaderValueValidator` extend `ValueValidator` but that pollutes the new interface with an unnecessary `validate(V value)`.~~\r\n\r\n~~WDYT ?~~\r\n\r\nI ended up catching and throwing, because we do it many places in the codebase.", "Throwing a stack trace is nothing less than making applications vulnerable to Denial-of-Service (DoS). This can be abused easily.\r\n\r\nConsider making it stackless.", "@normanmaurer WDYT?", "I am not inclined to make this exception stackless, at the very most I can maybe remove the cause, but making it stackless severely hampers debugging ability and is not even the standard norm in the Netty codebase.\r\n\r\n> Throwing a stack trace is nothing less than making applications vulnerable to Denial-of-Service (DoS)\r\n\r\nIf someone is trying to DoS an application by sending invalid headers, I don't think generating an exception stacktrace would be the bottleneck. Logging the stack trace might be but there are other mitigations for that in the logger configurations which applications need to use anyways.", "No need to concat the message. It will be part of the wrapped cause anyway. \r\n```suggestion\r\n throw new IllegalArgumentException(\"Validation failed for header '\" + name + \"'\", e);\r\n```", "I agree with @adwsingh here... I think its ok to just wrap.", "I will do profiling in the future for this and see how things behave in stack trace vs stackless." ]
"2023-02-10T09:22:22Z"
[]
Display which header failed validation
### Expected behavior Currently if a HeaderValue fails validation we get an IllegalArgumentException which has the message `a header value contains prohibited character {some_invalid_character} at index {index}`. Seeing this in production makes it hard to debug which header is having this problem. ### Actual behavior We should instead have the message, `Header value for {header_name} contains prohibited character {some_invalid_character} at index {index} To fix this I am suggesting to change the interface of ValueValidator to also take in the key which will be purely used for adding debug information.
[ "codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java" ]
[ "codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/DefaultHttpHeadersTest.java" ]
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 6abe71be0e2..6ff05fd6acb 100644 --- a/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java +++ b/codec/src/main/java/io/netty/handler/codec/DefaultHeaders.java @@ -1013,7 +1013,11 @@ protected void validateName(NameValidator<K> validator, boolean forAdd, K name) } protected void validateValue(ValueValidator<V> validator, K name, V value) { - validator.validate(value); + try { + validator.validate(value); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Validation failed for header '" + name + "'", e); + } } protected HeaderEntry<K, V> newHeaderEntry(int h, K name, V value, HeaderEntry<K, V> next) {
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 4cd1beedfe3..77e6fd37629 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 @@ -238,23 +238,25 @@ public void setObjectIterable() { @Test public void setCharSequenceValidatesValue() { final DefaultHttpHeaders headers = newDefaultDefaultHttpHeaders(); - assertThrows(IllegalArgumentException.class, new Executable() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() throws Throwable { headers.set(HEADER_NAME, ILLEGAL_VALUE); } }); + assertTrue(exception.getMessage().contains(HEADER_NAME)); } @Test public void setIterableValidatesValue() { final DefaultHttpHeaders headers = newDefaultDefaultHttpHeaders(); - assertThrows(IllegalArgumentException.class, new Executable() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, new Executable() { @Override public void execute() throws Throwable { headers.set(HEADER_NAME, Collections.singleton(ILLEGAL_VALUE)); } }); + assertTrue(exception.getMessage().contains(HEADER_NAME)); } @Test
train
test
"2023-02-14T11:05:12"
"2023-02-10T09:12:50Z"
adwsingh
val
netty/netty/13235_13238
netty/netty
netty/netty/13235
netty/netty/13238
[ "keyword_issue_to_pr" ]
24a0ac36ea91d1aee647d738f879ac873892d829
1314ede822a4a94be2446042d4b112649ae9ddc7
[ ">Netty version Used : 1.0.24\r\n\r\n\r\n@adhanoti Is this version, Reactor Netty version?\r\n\r\nIf yes then may be we would better discuss this in Reactor Netty issue tracker", "Thanks. Yes it is reactor netty version.\n\nDo i need to create separate issue?\n\nRegards,\nAshish\n\nOn Tue, Feb 21, 2023 at 12:07 PM Violeta Georgieva ***@***.***>\nwrote:\n\n> Netty version Used : 1.0.24\n>\n> @adhanoti <https://github.com/adhanoti> Is this version, Reactor Netty\n> version?\n>\n> If yes then may be we would better discuss this in Reactor Netty issue\n> tracker\n>\n> —\n> Reply to this email directly, view it on GitHub\n> <https://github.com/netty/netty/issues/13235#issuecomment-1437929581>, or\n> unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AK5F3SMW3DUUTUI7RB3HXW3WYRPCLANCNFSM6AAAAAAVCUIW2I>\n> .\n> You are receiving this because you were mentioned.Message ID:\n> ***@***.***>\n>\n", "yes please", "RFC non complaince : RFC 7540 \"Hypertext Transfer Protocol Version 2\n(HTTP/2)\" https://datatracker.ietf.org/doc/html/rfc7540 · Issue #2702 ·\nreactor/reactor-netty (github.com)\n<https://github.com/reactor/reactor-netty/issues/2702>\n\nTicket Created.\n\nLet me know if you need wireshark for same. In ticket i am not able to\nupload wireshark.\n\nRegards,\nAshish\n\nOn Tue, Feb 21, 2023 at 12:18 PM Violeta Georgieva ***@***.***>\nwrote:\n\n> yes please\n>\n> —\n> Reply to this email directly, view it on GitHub\n> <https://github.com/netty/netty/issues/13235#issuecomment-1437937763>, or\n> unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/AK5F3SIQG5XSC3UIIN2YKN3WYRQMBANCNFSM6AAAAAAVCUIW2I>\n> .\n> You are receiving this because you were mentioned.Message ID:\n> ***@***.***>\n>\n", "@normanmaurer @chrisvest @idelpivnitskiy This PR #12975 removes `:path` not empty check. IMO we should keep it. Wdyt?", "hm ... it was checking before for duplicate pseudo-header ... ok ignore my comment above", "@adhanoti The issue with `:path` should be address with #13238\r\n\r\nThe issue with `connection-specific header` should be address with #12975", "@normanmaurer @chrisvest @idelpivnitskiy \r\n\r\nThe issue with `Content-Length` that is not matching the actual data is interesting.\r\nNetty correctly identifies that there is a mismatch and throws a stream error.\r\n\r\n`Http2ConnectionHandler` correctly resets the stream with `PROTOCOL_ERROR`\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java#L744\r\n\r\nHowever when `Http2FrameCodec` and `Http2MultiplexHandler`, the flow is the following:\r\n\r\n`Http2FrameCodec` forwards the stream error\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodec.java#L568\r\n\r\n`Http2MultiplexHandler` notifies the child channel and closes it.\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2MultiplexHandler.java#L274-L278\r\n\r\nWhen the stream channel is closed, it is closed always with `CANCEL`\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2StreamChannel.java#L681\r\n\r\n I don't see a way to propagate the actual error code :(\r\n", "@violetagg let me have a look ", "This should be fixed by https://github.com/netty/netty/pull/13309" ]
[ "These lines should be moved into the `VALUE_VALIDATOR` on line 86.", "The `VALUE_VALIDATOR` receives only the value. How can we match name `:path` with the value?\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java#L86-L95\r\n\r\nAlso `Http2FrameCodecBuilder ` always builds `DefaultHttp2HeadersDecoder` with value validation disabled.\r\nhttps://github.com/netty/netty/blob/59aa6e635b9996cf21cd946e64353270679adc73/codec-http2/src/main/java/io/netty/handler/codec/http2/Http2FrameCodecBuilder.java#L208-L210", "Thanks for finding this missed case @violetagg.\r\nAfter reading the whole [RFC section 8.3](https://datatracker.ietf.org/doc/html/rfc9113#section-8.3), it sounds like any pseudo-header filed must not be empty, not only the `:path`. The only legit way is to omit a pseudo-header. WDYT?\r\n\r\nPerforming the check inside `DefaultHttp2Headers` seem reasonable, we just need to find a good spot where we have access to both name and value. I don't have any better idea except `validateValue` method as it's right now. ", "We need to protect this validation by a configuration flag to make sure users can disable it.\r\n\r\nTaking into account the RFC requirements to always run this validation (at least by default), the fact that `validateValues == false` by default, I would propose to use `validate` flag that controls header name validation. While in practice the check validates a value, I would say that technically it's a \"validation of a preudo-header name\". The purpose of `validateValues` is quite different. It's disabled by default because it will cause significant perf overhead for most users.", "Agree", "Please check the new commit.", "> Taking into account the RFC requirements to always run this validation (at least by default), the fact that validateValues == false by default, I would propose to use validate flag that controls header name validation.\r\n\r\n@idelpivnitskiy Is this \"always\" requirement any different from checking that byte ranges for values are valid, which we skip by default?", "The biggest differences are:\r\n1. the cost associated with a check\r\n2. how likely is it to hit the problem (messing up with pseudo-headers seems more likely)\r\n3. how it will affect the h2-protocol related flow vs user's business logic (having a bad char in some header won't impact h2 codec or h2->h1 transition)\r\n4. is the header name required to perform the check\r\n\r\nThis case seems to me close to `TE` header validation we have in `HpackDecoder`." ]
"2023-02-22T08:54:46Z"
[]
RFC non complaince : RFC 7540 "Hypertext Transfer Protocol Version 2 (HTTP/2)" https://datatracker.ietf.org/doc/html/rfc7540
**RFC behavior :** RFC7540 Section 8.1.2.3 : "All HTTP/2 requests MUST include exactly one valid value for the ":method", ":scheme", and ":path" pseudo-header field, unless it is a CONNECT request. An HTTP request that omits mandatory pseudo-header fields is malformed." RFC7540 Section 8.1.2.6 "Malformed requests or responses that are detected MUST be treated as a stream error (Section 5.4.2) of type PROTOCOL_ERROR" RFC7540 Section 5.4.2 : "An endpoint that detects a stream error sends a RST_STREAM frame (Section 6.4) that contains the stream identifier of the stream where the error occurred. The RST_STREAM frame includes an error code that indicates the type of error." Actaul Issue - NRF is our network function. Empty Path: NRF does not reset the stream when :path pseudo-header field is empty (without /). See: 221003-114918_SBA_conformance_pseudoHeadersEmptyPath_172.19.124.pcap Invalid Content-Length: NRF sends RST_STREAM with CANCEL reason instead of PROTOCOL_ERROR when content-length header is no correct for sent data. See: 221003-114925_SBA_conformance_forbiddenHeadersContentLength_172.19.124.pcap Invalid Connection-Specific header fields. RFC7540 Section 8.1.2.2 "Connection-Specific Header Fields" https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.2 Noted: Only valid connection-specific header field is "te" and must have value of "trailers" NRF does not reset stream when receiving a te header with a value other than "trailers" See: 221003-114929_SBA_conformance_forbiddenHeadersTE_172.19.124.pcap NRF does not reset stream when receiving a request with other connection-specific header fields. See: 221003-114932_SBA_conformance_forbiddenHeadersTransferEncoding_172.19.124.pcap for "transfer-encoding" and 221003-114939_SBA_conformance_forbiddenHeadersKeepAlive_172.19.124.pcap for "keep-alive" **Netty version Used** : 1.0.24 **Java version used** : 17 Need to know whether Netty follow RFC 7540 and when the compliance will be available.
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackDecoderTest.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/DefaultHttp2Headers.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java index 91a6545b763..60a2925873c 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java @@ -175,6 +175,13 @@ protected void validateName(NameValidator<CharSequence> validator, boolean forAd protected void validateValue(ValueValidator<CharSequence> validator, CharSequence name, CharSequence value) { // This method has a noop override for backward compatibility, see https://github.com/netty/netty/pull/12975 super.validateValue(validator, name, value); + // https://datatracker.ietf.org/doc/html/rfc9113#section-8.3.1 + // pseudo headers must not be empty + if (nameValidator() == HTTP2_NAME_VALIDATOR && (value == null || value.length() == 0) && + hasPseudoHeaderFormat(name)) { + PlatformDependent.throwException(connectionError( + PROTOCOL_ERROR, "HTTP/2 pseudo-header '%s' must not be empty.", name)); + } } @Override
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 e376197f12b..f70f528e6ca 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 @@ -33,6 +33,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import io.netty.util.AsciiString; import io.netty.util.internal.StringUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -54,6 +55,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockingDetails; @@ -863,4 +865,50 @@ public void execute() throws Throwable { in2.release(); } } + + @ParameterizedTest + @CsvSource(value = {":method,''", ":scheme,''", ":authority,''", ":path,''"}) + public void testPseudoHeaderEmptyValidationEnabled(String name, String value) throws Exception { + final ByteBuf in = Unpooled.buffer(200); + try { + HpackEncoder hpackEncoder = new HpackEncoder(true); + + Http2Headers toEncode = new InOrderHttp2Headers(); + toEncode.add(name, value); + hpackEncoder.encodeHeaders(1, in, toEncode, NEVER_SENSITIVE); + + final Http2Headers decoded = new DefaultHttp2Headers(); + + Http2Exception.StreamException e = assertThrows(Http2Exception.StreamException.class, new Executable() { + @Override + public void execute() throws Throwable { + hpackDecoder.decode(3, in, decoded, true); + } + }); + assertThat(e.streamId(), is(3)); + assertThat(e.error(), is(PROTOCOL_ERROR)); + } finally { + in.release(); + } + } + + @ParameterizedTest + @CsvSource(value = {":method,''", ":scheme,''", ":authority,''", ":path,''"}) + public void testPseudoHeaderEmptyValidationDisabled(String name, String value) throws Exception { + final ByteBuf in = Unpooled.buffer(200); + try { + HpackEncoder hpackEncoder = new HpackEncoder(true); + + Http2Headers toEncode = new InOrderHttp2Headers(); + toEncode.add(name, value); + hpackEncoder.encodeHeaders(1, in, toEncode, NEVER_SENSITIVE); + + final Http2Headers decoded = new DefaultHttp2Headers(false); + hpackDecoder.decode(3, in, decoded, true); + + assertSame(AsciiString.EMPTY_STRING, decoded.get(name)); + } finally { + in.release(); + } + } } 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 29e6da98ce9..365dbdad83d 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 @@ -83,8 +83,20 @@ public void setHttp2AuthorityNullOrEmpty() { HttpConversionUtil.setHttp2Authority(null, headers); assertNull(headers.authority()); - HttpConversionUtil.setHttp2Authority("", headers); - assertSame(AsciiString.EMPTY_STRING, headers.authority()); + // https://datatracker.ietf.org/doc/html/rfc9113#section-8.3.1 + // Clients that generate HTTP/2 requests directly MUST use the ":authority" pseudo-header + // field to convey authority information, unless there is no authority information to convey + // (in which case it MUST NOT generate ":authority"). + // An intermediary that forwards a request over HTTP/2 MUST construct an ":authority" pseudo-header + // field using the authority information from the control data of the original request, unless the + // original request's target URI does not contain authority information + // (in which case it MUST NOT generate ":authority"). + assertThrows(Http2Exception.class, new Executable() { + @Override + public void execute() { + HttpConversionUtil.setHttp2Authority("", new DefaultHttp2Headers()); + } + }); } @Test
train
test
"2023-04-03T12:18:53"
"2023-02-21T06:32:31Z"
adhanoti
val
netty/netty/13307_13312
netty/netty
netty/netty/13307
netty/netty/13312
[ "keyword_pr_to_issue" ]
ccc5e01f0444301561f055b02cd7c1f3e875bca7
cd540193b98e1ffb9cdaaf2629e4a6d28665a2c5
[ "Extend the `HttpContentDecompressor` and override the `newContentDecoder` for Snappy and delegate the rest to `super#newContentDecoder`.", "> Extend the `HttpContentDecompressor` and override the `newContentDecoder` for Snappy and delegate the rest to `super#newContentDecoder`.\r\n\r\nThanks for the guidance @hyperxpro, I assume this means Pr's are welcome ? I'll be working on it then ^^", "They're! ^^" ]
[ "```suggestion\r\n if (SNAPPY.contentEqualsIgnoreCase(contentEncoding)) {\r\n```", "```suggestion\r\n \r\n```", "```suggestion\r\n -22, 104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100\r\n```", "```suggestion\r\n```", "```suggestion\r\n```", "```suggestion\r\n return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),\r\n```" ]
"2023-03-30T19:36:44Z"
[]
Extend decompression of HttpContentDecompressor.java
### Actual behaviour At the moment the [HttpContentDecompressor.java](https://github.com/netty/netty/blob/cf5c467f4ead5ba5e1e36f5c4903af78bd49c35c/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java#LL58C9-L73) support: - deflate - gzip - brotli I wonder if we should extend it ? I am specifically in need of supporting `snappy` ```java if (GZIP.contentEqualsIgnoreCase(contentEncoding) || X_GZIP.contentEqualsIgnoreCase(contentEncoding)) { return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP)); } if (DEFLATE.contentEqualsIgnoreCase(contentEncoding) || X_DEFLATE.contentEqualsIgnoreCase(contentEncoding)) { final ZlibWrapper wrapper = strict ? ZlibWrapper.ZLIB : ZlibWrapper.ZLIB_OR_NONE; // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly. return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), ZlibCodecFactory.newZlibDecoder(wrapper)); } if (Brotli.isAvailable() && BR.contentEqualsIgnoreCase(contentEncoding)) { return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), ctx.channel().config(), new BrotliDecoder()); } ``` I am opening this issue to talk about that. Is it something Netty would be interested in seeing happening ? I could be doing the PR if needed. ### Netty version 4.1
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java", "codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java index d66151d463c..e8e1d909723 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpContentDecompressor.java @@ -20,12 +20,14 @@ import static io.netty.handler.codec.http.HttpHeaderValues.GZIP; import static io.netty.handler.codec.http.HttpHeaderValues.X_DEFLATE; import static io.netty.handler.codec.http.HttpHeaderValues.X_GZIP; +import static io.netty.handler.codec.http.HttpHeaderValues.SNAPPY; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.compression.Brotli; import io.netty.handler.codec.compression.BrotliDecoder; import io.netty.handler.codec.compression.ZlibCodecFactory; import io.netty.handler.codec.compression.ZlibWrapper; +import io.netty.handler.codec.compression.SnappyFrameDecoder; /** * Decompresses an {@link HttpMessage} and an {@link HttpContent} compressed in @@ -72,6 +74,11 @@ protected EmbeddedChannel newContentDecoder(String contentEncoding) throws Excep ctx.channel().config(), new BrotliDecoder()); } + if (SNAPPY.contentEqualsIgnoreCase(contentEncoding)) { + return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(), + ctx.channel().config(), new SnappyFrameDecoder()); + } + // 'identity' or unsupported return null; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java b/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java index 5fb10861290..6b09c1614b3 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValues.java @@ -119,6 +119,12 @@ public final class HttpHeaderValues { * {@code "br"} */ public static final AsciiString BR = AsciiString.cached("br"); + + /** + * {@code "snappy"} + */ + public static final AsciiString SNAPPY = AsciiString.cached("snappy"); + /** * {@code "zstd"} */
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java index 71ddb15213a..aeca8dcf3c2 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/HttpContentDecoderTest.java @@ -56,6 +56,10 @@ public class HttpContentDecoderTest { 31, -117, 8, 8, 12, 3, -74, 84, 0, 3, 50, 0, -53, 72, -51, -55, -55, -41, 81, 40, -49, 47, -54, 73, 1, 0, 58, 114, -85, -1, 12, 0, 0, 0 }; + private static final byte[] SNAPPY_HELLO_WORLD = { + -1, 6, 0, 0, 115, 78, 97, 80, 112, 89, 1, 16, 0, 0, 11, -66, -63, + -22, 104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100 + }; private static final String SAMPLE_STRING = "Hello, I am Meow!. A small kitten. :)" + "I sleep all day, and meow all night."; private static final byte[] SAMPLE_BZ_BYTES = new byte[]{27, 72, 0, 0, -60, -102, 91, -86, 103, 20, @@ -147,7 +151,7 @@ public void testChunkedRequestDecompression() { } @Test - public void testResponseDecompression() { + public void testSnappyResponseDecompression() { // baseline test: response decoder, content decompressor && request aggregator work as expected HttpResponseDecoder decoder = new HttpResponseDecoder(); HttpContentDecoder decompressor = new HttpContentDecompressor(); @@ -155,9 +159,37 @@ public void testResponseDecompression() { EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); String headers = "HTTP/1.1 200 OK\r\n" + - "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + - "Content-Encoding: gzip\r\n" + + "Content-Length: " + SNAPPY_HELLO_WORLD.length + "\r\n" + + "Content-Encoding: snappy\r\n" + "\r\n"; + ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.UTF_8), SNAPPY_HELLO_WORLD); + assertTrue(channel.writeInbound(buf)); + + Object o = channel.readInbound(); + assertThat(o, is(instanceOf(FullHttpResponse.class))); + FullHttpResponse resp = (FullHttpResponse) o; + assertEquals(HELLO_WORLD.length(), resp.headers().getInt(HttpHeaderNames.CONTENT_LENGTH).intValue()); + assertEquals(HELLO_WORLD, resp.content().toString(CharsetUtil.UTF_8)); + resp.release(); + + assertHasInboundMessages(channel, false); + assertHasOutboundMessages(channel, false); + assertFalse(channel.finish()); // assert that no messages are left in channel + } + + @Test + public void testResponseDecompression() { + // baseline test: response decoder, content decompressor && request aggregator work as expected + HttpResponseDecoder decoder = new HttpResponseDecoder(); + HttpContentDecoder decompressor = new HttpContentDecompressor(); + HttpObjectAggregator aggregator = new HttpObjectAggregator(1024); + + EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, aggregator); + + String headers = "HTTP/1.1 200 OK\r\n" + + "Content-Length: " + GZ_HELLO_WORLD.length + "\r\n" + + "Content-Encoding: gzip\r\n" + + "\r\n"; ByteBuf buf = Unpooled.copiedBuffer(headers.getBytes(CharsetUtil.US_ASCII), GZ_HELLO_WORLD); assertTrue(channel.writeInbound(buf));
val
test
"2023-03-29T12:35:58"
"2023-03-29T13:52:42Z"
redcinelli
val
netty/netty/13335_13336
netty/netty
netty/netty/13335
netty/netty/13336
[ "keyword_pr_to_issue" ]
1314ede822a4a94be2446042d4b112649ae9ddc7
de876d197a945e2b3a4a96b90a65c00611b77806
[]
[ "should this be `execute(task, false)`?", "check `SingleThreadEventExecutor::lazyExecute` overridden method:\r\n\r\n```java\r\n @Override\r\n public void lazyExecute(Runnable task) {\r\n lazyExecute0(task);\r\n }\r\n\r\n private void lazyExecute0(@Schedule Runnable task) {\r\n execute(ObjectUtil.checkNotNull(task, \"task\"), false);\r\n }\r\n```", "```suggestion\r\n * @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour\r\n```", "```suggestion\r\n * @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour\r\n```" ]
"2023-04-17T09:51:25Z"
[ "cleanup" ]
Deprecates LazyRunnable
https://ionutbalosin.com/2023/03/jvm-performance-comparison-for-jdk-17/#typecheckbenchmark shows how bad currently JITs handle type checking of interfaces not implemented by a concrete type. I've built an [agent](https://github.com/RedHatPerf/type-pollution-agent) that can detect such slow paths and by using it in a https://hyperfoil.io/ workload it has reported: ``` -------------------------- 5: io.vertx.core.net.impl.ConnectionBase$$Lambda$281/0x0000000800fd0fc8 Count: 3065706 Types: io.netty.util.concurrent.AbstractEventExecutor$LazyRunnable Traces: io.netty.util.concurrent.SingleThreadEventExecutor.execute0(SingleThreadEventExecutor.java:827) class: io.netty.util.concurrent.AbstractEventExecutor$LazyRunnable count: 3065706 -------------------------- 6: io.vertx.core.http.impl.Http1xServerConnection$$Lambda$284/0x0000000800fd2330 Count: 3064004 Types: io.netty.util.concurrent.AbstractEventExecutor$LazyRunnable Traces: io.netty.util.concurrent.SingleThreadEventExecutor.execute0(SingleThreadEventExecutor.java:827) class: io.netty.util.concurrent.AbstractEventExecutor$LazyRunnable count: 3064004 -------------------------- ``` that means that event submission always receive such hit, without providing any benefit for such a common use case. I'm sending a PR to deprecate it on Netty 4.1 @njhill Let me know if you need any more info about the issue
[ "common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java", "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java", "transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java" ]
[ "common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java", "common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java", "transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java" ]
[ "common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java" ]
diff --git a/common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java b/common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java index ce6b1ac875f..b32978ee679 100644 --- a/common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/AbstractEventExecutor.java @@ -177,25 +177,19 @@ protected static void runTask(@Execute Runnable task) { /** * Like {@link #execute(Runnable)} but does not guarantee the task will be run until either * a non-lazy task is executed or the executor is shut down. - * - * This is equivalent to submitting a {@link AbstractEventExecutor.LazyRunnable} to - * {@link #execute(Runnable)} but for an arbitrary {@link Runnable}. - * + * <p> * The default implementation just delegates to {@link #execute(Runnable)}. + * </p> */ @UnstableApi public void lazyExecute(Runnable task) { - lazyExecute0(task); - } - - private void lazyExecute0(@Schedule Runnable task) { execute(task); } /** - * Marker interface for {@link Runnable} to indicate that it should be queued for execution - * but does not need to run immediately. + * @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour + * */ - @UnstableApi + @Deprecated public interface LazyRunnable extends Runnable { } } 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 6c7020ee234..070b2fdfff6 100644 --- a/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java +++ b/common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java @@ -824,7 +824,7 @@ public void lazyExecute(Runnable task) { private void execute0(@Schedule Runnable task) { ObjectUtil.checkNotNull(task, "task"); - execute(task, !(task instanceof LazyRunnable) && wakesUpForTask(task)); + execute(task, wakesUpForTask(task)); } private void lazyExecute0(@Schedule Runnable task) { @@ -917,7 +917,7 @@ public final ThreadProperties threadProperties() { } /** - * @deprecated use {@link AbstractEventExecutor.LazyRunnable} + * @deprecated override {@link SingleThreadEventExecutor#wakesUpForTask} to re-create this behaviour */ @Deprecated protected interface NonWakeupRunnable extends LazyRunnable { } diff --git a/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java b/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java index 5e2acb1209f..f7136c62714 100644 --- a/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java +++ b/transport/src/main/java/io/netty/channel/SingleThreadEventLoop.java @@ -115,7 +115,7 @@ public final void executeAfterEventLoopIteration(Runnable task) { reject(task); } - if (!(task instanceof LazyRunnable) && wakesUpForTask(task)) { + if (wakesUpForTask(task)) { wakeup(inEventLoop()); } }
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 8465ea8d3ae..dc12034bcc5 100644 --- a/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java +++ b/common/src/test/java/io/netty/util/concurrent/SingleThreadEventExecutorTest.java @@ -17,7 +17,6 @@ import org.junit.jupiter.api.Test; -import io.netty.util.concurrent.AbstractEventExecutor.LazyRunnable; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.function.Executable; @@ -208,12 +207,18 @@ public void run() { } } - static class LazyLatchTask extends LatchTask implements LazyRunnable { } + static class LazyLatchTask extends LatchTask { } @Test public void testLazyExecution() throws Exception { final SingleThreadEventExecutor executor = new SingleThreadEventExecutor(null, Executors.defaultThreadFactory(), false) { + + @Override + protected boolean wakesUpForTask(final Runnable task) { + return !(task instanceof LazyLatchTask); + } + @Override protected void run() { while (!confirmShutdown()) {
test
test
"2023-04-16T02:01:52"
"2023-04-17T09:45:03Z"
franz1981
val
netty/netty/13337_13338
netty/netty
netty/netty/13337
netty/netty/13338
[ "keyword_issue_to_pr", "keyword_pr_to_issue" ]
1314ede822a4a94be2446042d4b112649ae9ddc7
f2eca0f4e9bed48e6b139c30d626a9368249942f
[ "This is either because you don't have an `HttpRequestDecoder` or a `HttpServerCodec` in your pipeline, or something else in your pipeline dropped the handshake response in the write path.", "If the pipeline checks fail, how can i release the handshake response.", "> If the pipeline checks fail, how can i release the handshake response.\r\n\r\nYou can't. It's a bug in Netty that we'll fix with #13338" ]
[]
"2023-04-17T14:42:48Z"
[]
WebSocketServerHandshaker.handshake not call ByteBuf.release()
### Expected behavior 2023-02-08 01:32:25.622 [nioEventLoopGroup-3-11-] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() was not called before it's garbage-collected. See https://netty.io/wiki/reference-counted-objects.html for more information. Recent access records: Created at: io.netty.buffer.PooledByteBufAllocator.newDirectBuffer(PooledByteBufAllocator.java:349) io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:187) io.netty.buffer.AbstractByteBufAllocator.directBuffer(AbstractByteBufAllocator.java:178) io.netty.buffer.AbstractByteBufAllocator.buffer(AbstractByteBufAllocator.java:115) io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker13.newHandshakeResponse(WebSocketServerHandshaker13.java:143) io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker.handshake(WebSocketServerHandshaker.java:194) io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker.handshake(WebSocketServerHandshaker.java:169) com.game.netty.handler.WsServerProtocolHandler.lambda$channelRead$0(WsServerProtocolHandler.java:65) ### Actual behavior ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) public final ChannelFuture handshake(Channel channel, FullHttpRequest req, HttpHeaders responseHeaders, final ChannelPromise promise) { if (logger.isDebugEnabled()) { logger.debug("{} WebSocket version {} server handshake", channel, this.version()); } ChannelPipeline p = channel.pipeline(); if (p.get(HttpObjectAggregator.class) != null) { p.remove(HttpObjectAggregator.class); } if (p.get(HttpContentCompressor.class) != null) { p.remove(HttpContentCompressor.class); } ChannelHandlerContext ctx = p.context(HttpRequestDecoder.class); final String encoderName; if (ctx == null) { ctx = p.context(HttpServerCodec.class); if (ctx == null) { promise.setFailure(new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline")); return promise; } p.addBefore(ctx.name(), "wsencoder", this.newWebSocketEncoder()); p.addBefore(ctx.name(), "wsdecoder", this.newWebsocketDecoder()); encoderName = ctx.name(); } else { p.replace(ctx.name(), "wsdecoder", this.newWebsocketDecoder()); encoderName = p.context(HttpResponseEncoder.class).name(); p.addBefore(encoderName, "wsencoder", this.newWebSocketEncoder()); } FullHttpResponse response = this.newHandshakeResponse(req, responseHeaders); channel.writeAndFlush(response).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ChannelPipeline p = future.channel().pipeline(); p.remove(encoderName); promise.setSuccess(); } else { promise.setFailure(future.cause()); } } }); return promise; } ### Netty version 4.1.91.Final ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java" ]
[]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java index 3c3fac5a49c..5271102b7eb 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketServerHandshaker.java @@ -215,6 +215,7 @@ public final ChannelFuture handshake(Channel channel, FullHttpRequest req, if (ctx == null) { promise.setFailure( new IllegalStateException("No HttpDecoder and no HttpServerCodec in the pipeline")); + response.release(); return promise; } p.addBefore(ctx.name(), "wsencoder", newWebSocketEncoder());
null
test
test
"2023-04-16T02:01:52"
"2023-04-17T14:02:11Z"
fengxuehan
val
netty/netty/13384_13386
netty/netty
netty/netty/13384
netty/netty/13386
[ "keyword_pr_to_issue" ]
af132ffc483f68d06eed746797fff2af652bcd35
91f484371b8db359bab06df691e2d3d0300a4670
[ "You can specify a CNAME cache by calling `DnsNameResolverBuilder.cnameCache(DnsCnameCache)`, specifying `new DefaultDnsCnameCache()` with the desired min/max TTL values. Would this work for you?", "Thanks for the response, Trustin. This would work, but it feels like a workaround as opposed to allowing ttl values to be set for the other caches via the ttl fields", "@trustin I think it is a bit inconvenient to have configured either all types of caches or to leave them all default based on the TTLs. I prepared one change can you take a look at this #13386?" ]
[]
"2023-05-17T06:17:45Z"
[]
Unable to supply resolveCache to DnsNameResolverBuilder and use TTL's for other two caches
### Expected behavior If a resolveCache is set in the DnsNameResolverBuilder the min, max and negative TTL fields must be null. However, this means the cname cache and authoritative DNS server cache will be built with default (fallback) TTLs as opposed to a TTL which the user may want to set. I'd expect to be able to provide the resolveCache and also TTL's which should be applied to the cname and authoritative DNS server caches. This is not possible due to the following code: ``` if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { throw new IllegalStateException("resolveCache and TTLs are mutually exclusive"); } if (authoritativeDnsServerCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { throw new IllegalStateException("authoritativeDnsServerCache and TTLs are mutually exclusive"); } ``` This means the building of the cname cache is forced to use default values (0, Integer.MAX_VALUE) ``` private DnsCnameCache newCnameCache() { return new DefaultDnsCnameCache( intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE)); } ``` ### Actual behavior ### Steps to reproduce Use DnsNameResolverBuilder to with a supplied resolveCache and minTtl, maxTtl or negativeTtl values. ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.92 ### JVM version (e.g. `java -version`) ### OS version (e.g. `uname -a`)
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java" ]
[ "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java", "resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java" ]
[ "resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverBuilderTest.java" ]
diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java index c29f7b866b9..b75db05a7da 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultAuthoritativeDnsServerCache.java @@ -123,4 +123,14 @@ public String toString() { return "DefaultAuthoritativeDnsServerCache(minTtl=" + minTtl + ", maxTtl=" + maxTtl + ", cached nameservers=" + resolveCache.size() + ')'; } + + // Package visibility for testing purposes + int minTtl() { + return minTtl; + } + + // Package visibility for testing purposes + int maxTtl() { + return maxTtl; + } } diff --git a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java index 8395a67f6bd..9f5c6d0397c 100644 --- a/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java +++ b/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCnameCache.java @@ -92,4 +92,14 @@ public void clear() { public boolean clear(String hostname) { return cache.clear(checkNotNull(hostname, "hostname")); } + + // Package visibility for testing purposes + int minTtl() { + return minTtl; + } + + // Package visibility for testing purposes + int maxTtl() { + return maxTtl; + } } 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 d3bfb191dc3..7e430338ba3 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,8 @@ import io.netty.resolver.ResolvedAddressTypes; import io.netty.util.concurrent.Future; import io.netty.util.internal.ObjectUtil; +import io.netty.util.internal.logging.InternalLogger; +import io.netty.util.internal.logging.InternalLoggerFactory; import java.net.SocketAddress; import java.util.ArrayList; @@ -38,6 +40,9 @@ * A {@link DnsNameResolver} builder. */ public final class DnsNameResolverBuilder { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsNameResolverBuilder.class); + volatile EventLoop eventLoop; private ChannelFactory<? extends DatagramChannel> channelFactory; private ChannelFactory<? extends SocketChannel> socketChannelFactory; @@ -491,11 +496,15 @@ public DnsNameResolver build() { } if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { - throw new IllegalStateException("resolveCache and TTLs are mutually exclusive"); + logger.debug("resolveCache and TTLs are mutually exclusive. TTLs are ignored."); + } + + if (cnameCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { + logger.debug("cnameCache and TTLs are mutually exclusive. TTLs are ignored."); } if (authoritativeDnsServerCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) { - throw new IllegalStateException("authoritativeDnsServerCache and TTLs are mutually exclusive"); + logger.debug("authoritativeDnsServerCache and TTLs are mutually exclusive. TTLs are ignored."); } DnsCache resolveCache = this.resolveCache != null ? this.resolveCache : newCache();
diff --git a/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverBuilderTest.java b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverBuilderTest.java new file mode 100644 index 00000000000..bfe7bfb4740 --- /dev/null +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverBuilderTest.java @@ -0,0 +1,241 @@ +/* + * Copyright 2023 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: + * + * https://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.channel.EventLoop; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioDatagramChannel; +import io.netty.handler.codec.dns.DnsRecord; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.List; + +import static io.netty.resolver.dns.Cache.MAX_SUPPORTED_TTL_SECS; +import static org.assertj.core.api.Assertions.assertThat; + +class DnsNameResolverBuilderTest { + private static final EventLoopGroup GROUP = new NioEventLoopGroup(1); + + private DnsNameResolverBuilder builder; + private DnsNameResolver resolver; + + @BeforeEach + void setUp() { + builder = new DnsNameResolverBuilder(GROUP.next()).channelType(NioDatagramChannel.class); + } + + @AfterEach + void tearDown() { + if (resolver != null) { + resolver.close(); + } + } + + @AfterAll + static void shutdownEventLoopGroup() { + GROUP.shutdownGracefully(); + } + + @Test + void testDefaults() { + resolver = builder.build(); + + checkDefaultDnsCache((DefaultDnsCache) resolver.resolveCache(), MAX_SUPPORTED_TTL_SECS, 0, 0); + + checkDefaultDnsCnameCache((DefaultDnsCnameCache) resolver.cnameCache(), MAX_SUPPORTED_TTL_SECS, 0); + + checkDefaultAuthoritativeDnsServerCache( + (DefaultAuthoritativeDnsServerCache) resolver.authoritativeDnsServerCache(), MAX_SUPPORTED_TTL_SECS, 0); + } + + @Test + void testCustomDnsCacheDefaultTtl() { + DnsCache testDnsCache = new TestDnsCache(); + resolver = builder.resolveCache(testDnsCache).build(); + + assertThat(resolver.resolveCache()).isSameAs(testDnsCache); + + checkDefaultDnsCnameCache((DefaultDnsCnameCache) resolver.cnameCache(), MAX_SUPPORTED_TTL_SECS, 0); + + checkDefaultAuthoritativeDnsServerCache( + (DefaultAuthoritativeDnsServerCache) resolver.authoritativeDnsServerCache(), MAX_SUPPORTED_TTL_SECS, 0); + } + + @Test + void testCustomDnsCacheCustomTtl() { + DnsCache testDnsCache = new TestDnsCache(); + resolver = builder.resolveCache(testDnsCache).ttl(1, 2).negativeTtl(3).build(); + + assertThat(resolver.resolveCache()).isSameAs(testDnsCache); + + checkDefaultDnsCnameCache((DefaultDnsCnameCache) resolver.cnameCache(), 2, 1); + + checkDefaultAuthoritativeDnsServerCache( + (DefaultAuthoritativeDnsServerCache) resolver.authoritativeDnsServerCache(), 2, 1); + } + + @Test + void testCustomDnsCnameCacheDefaultTtl() { + DnsCnameCache testDnsCnameCache = new TestDnsCnameCache(); + resolver = builder.cnameCache(testDnsCnameCache).build(); + + checkDefaultDnsCache((DefaultDnsCache) resolver.resolveCache(), MAX_SUPPORTED_TTL_SECS, 0, 0); + + assertThat(resolver.cnameCache()).isSameAs(testDnsCnameCache); + + checkDefaultAuthoritativeDnsServerCache( + (DefaultAuthoritativeDnsServerCache) resolver.authoritativeDnsServerCache(), MAX_SUPPORTED_TTL_SECS, 0); + } + + @Test + void testCustomDnsCnameCacheCustomTtl() { + DnsCnameCache testDnsCnameCache = new TestDnsCnameCache(); + resolver = builder.cnameCache(testDnsCnameCache).ttl(1, 2).negativeTtl(3).build(); + + checkDefaultDnsCache((DefaultDnsCache) resolver.resolveCache(), 2, 1, 3); + + assertThat(resolver.cnameCache()).isSameAs(testDnsCnameCache); + + checkDefaultAuthoritativeDnsServerCache( + (DefaultAuthoritativeDnsServerCache) resolver.authoritativeDnsServerCache(), 2, 1); + } + + @Test + void testCustomAuthoritativeDnsServerCacheDefaultTtl() { + AuthoritativeDnsServerCache testAuthoritativeDnsServerCache = new TestAuthoritativeDnsServerCache(); + resolver = builder.authoritativeDnsServerCache(testAuthoritativeDnsServerCache).build(); + + checkDefaultDnsCache((DefaultDnsCache) resolver.resolveCache(), MAX_SUPPORTED_TTL_SECS, 0, 0); + + checkDefaultDnsCnameCache((DefaultDnsCnameCache) resolver.cnameCache(), MAX_SUPPORTED_TTL_SECS, 0); + + assertThat(resolver.authoritativeDnsServerCache()).isSameAs(testAuthoritativeDnsServerCache); + } + + @Test + void testCustomAuthoritativeDnsServerCacheCustomTtl() { + AuthoritativeDnsServerCache testAuthoritativeDnsServerCache = new TestAuthoritativeDnsServerCache(); + resolver = builder.authoritativeDnsServerCache(testAuthoritativeDnsServerCache) + .ttl(1, 2).negativeTtl(3).build(); + + checkDefaultDnsCache((DefaultDnsCache) resolver.resolveCache(), 2, 1, 3); + + checkDefaultDnsCnameCache((DefaultDnsCnameCache) resolver.cnameCache(), 2, 1); + + assertThat(resolver.authoritativeDnsServerCache()).isSameAs(testAuthoritativeDnsServerCache); + } + + private static void checkDefaultDnsCache(DefaultDnsCache dnsCache, + int expectedMaxTtl, int expectedMinTtl, int expectedNegativeTtl) { + assertThat(dnsCache.maxTtl()).isEqualTo(expectedMaxTtl); + assertThat(dnsCache.minTtl()).isEqualTo(expectedMinTtl); + assertThat(dnsCache.negativeTtl()).isEqualTo(expectedNegativeTtl); + } + + private static void checkDefaultDnsCnameCache(DefaultDnsCnameCache dnsCnameCache, + int expectedMaxTtl, int expectedMinTtl) { + assertThat(dnsCnameCache.maxTtl()).isEqualTo(expectedMaxTtl); + assertThat(dnsCnameCache.minTtl()).isEqualTo(expectedMinTtl); + } + + private static void checkDefaultAuthoritativeDnsServerCache( + DefaultAuthoritativeDnsServerCache authoritativeDnsServerCache, + int expectedMaxTtl, int expectedMinTtl) { + assertThat(authoritativeDnsServerCache.maxTtl()).isEqualTo(expectedMaxTtl); + assertThat(authoritativeDnsServerCache.minTtl()).isEqualTo(expectedMinTtl); + } + + private static final class TestDnsCache implements DnsCache { + + @Override + public void clear() { + //no-op + } + + @Override + public boolean clear(String hostname) { + return false; + } + + @Override + public List<? extends DnsCacheEntry> get(String hostname, DnsRecord[] additional) { + return null; + } + + @Override + public DnsCacheEntry cache(String hostname, DnsRecord[] additional, InetAddress address, + long originalTtl, EventLoop loop) { + return null; + } + + @Override + public DnsCacheEntry cache(String hostname, DnsRecord[] additional, Throwable cause, EventLoop loop) { + return null; + } + } + + private static final class TestDnsCnameCache implements DnsCnameCache { + + @Override + public String get(String hostname) { + return null; + } + + @Override + public void cache(String hostname, String cname, long originalTtl, EventLoop loop) { + //no-op + } + + @Override + public void clear() { + //no-op + } + + @Override + public boolean clear(String hostname) { + return false; + } + } + + private static final class TestAuthoritativeDnsServerCache implements AuthoritativeDnsServerCache { + + @Override + public DnsServerAddressStream get(String hostname) { + return null; + } + + @Override + public void cache(String hostname, InetSocketAddress address, long originalTtl, EventLoop loop) { + //no-op + } + + @Override + public void clear() { + //no-op + } + + @Override + public boolean clear(String hostname) { + return false; + } + } +}
train
test
"2023-05-15T16:00:32"
"2023-05-16T10:41:26Z"
samueldlightfoot
val
netty/netty/13417_13419
netty/netty
netty/netty/13417
netty/netty/13419
[ "keyword_pr_to_issue" ]
c1a6994455cea05c873502416cc34d7d9d9610ad
22ce6d17032c30307840744e5c4c38d7af189673
[ "thanks @violetagg " ]
[]
"2023-06-02T13:06:51Z"
[]
Domain socket channel local address is null
### Expected behavior The domain socket local address is not null. ### Actual behavior The domain socket local address is null. `QueueDomainSocketChannel#localAddress0()` returns `local` field which has never been set before (other than null at construction time and in `doConnect`). It should reflect the value in the file descriptor `fd` field instead. ### Steps to reproduce Create a client domain socket (bsd or epoll) connect to a server, then get the local channel address. ### Netty version [4.1.92.Final,)
[ "transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java", "transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java" ]
[ "transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java", "transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java" ]
[ "testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketAddressesTest.java" ]
diff --git a/transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java b/transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java index 0773e39133a..b72dd69fa5e 100644 --- a/transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java +++ b/transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollDomainSocketChannel.java @@ -87,7 +87,7 @@ public EpollDomainSocketChannelConfig config() { @Override protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { if (super.doConnect(remoteAddress, localAddress)) { - local = (DomainSocketAddress) localAddress; + local = localAddress != null ? (DomainSocketAddress) localAddress : socket.localDomainSocketAddress(); remote = (DomainSocketAddress) remoteAddress; return true; } diff --git a/transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java b/transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java index 6e99e9c3e63..6b5ee22900c 100644 --- a/transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java +++ b/transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueDomainSocketChannel.java @@ -80,7 +80,7 @@ public KQueueDomainSocketChannelConfig config() { @Override protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { if (super.doConnect(remoteAddress, localAddress)) { - local = (DomainSocketAddress) localAddress; + local = localAddress != null ? (DomainSocketAddress) localAddress : socket.localDomainSocketAddress(); remote = (DomainSocketAddress) remoteAddress; return true; }
diff --git a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketAddressesTest.java b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketAddressesTest.java index ecab824f887..dce8c082bd1 100644 --- a/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketAddressesTest.java +++ b/testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketAddressesTest.java @@ -39,14 +39,25 @@ public void testAddresses(TestInfo testInfo) throws Throwable { run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { @Override public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { - testAddresses(serverBootstrap, bootstrap); + testAddresses(serverBootstrap, bootstrap, true); + } + }); + } + + @Test + @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS) + public void testAddressesConnectWithoutLocalAddress(TestInfo testInfo) throws Throwable { + run(testInfo, new Runner<ServerBootstrap, Bootstrap>() { + @Override + public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable { + testAddresses(serverBootstrap, bootstrap, false); } }); } protected abstract void assertAddress(SocketAddress address); - private void testAddresses(ServerBootstrap sb, Bootstrap cb) throws Throwable { + private void testAddresses(ServerBootstrap sb, Bootstrap cb, boolean withLocalAddress) throws Throwable { Channel serverChannel = null; Channel clientChannel = null; try { @@ -65,7 +76,11 @@ public void channelActive(ChannelHandlerContext ctx) { assertNull(clientChannel.localAddress()); assertNull(clientChannel.remoteAddress()); - clientChannel.connect(serverChannel.localAddress(), newSocketAddress()).syncUninterruptibly().channel(); + if (withLocalAddress) { + clientChannel.connect(serverChannel.localAddress(), newSocketAddress()).syncUninterruptibly().channel(); + } else { + clientChannel.connect(serverChannel.localAddress()).syncUninterruptibly().channel(); + } assertAddress(clientChannel.localAddress()); assertAddress(clientChannel.remoteAddress());
val
test
"2023-06-01T14:00:12"
"2023-06-01T12:41:04Z"
vietj
val
netty/netty/13313_13451
netty/netty
netty/netty/13313
netty/netty/13451
[ "keyword_pr_to_issue" ]
22bf43b03999f40459c61b61c453e0989563cc98
dd2c2bbb723c9a10e3efc6d7bc2cc4a4720375e2
[ "Unfortunately, those pictures are not worth even a single word. That's too less information to conclude anything. \r\n\r\nWhat kind of workload is it? How many connections? Are you running blocking operations on EventLoop?", "> Unfortunately, those pictures are not worth even a single word. That's too less information to conclude anything.\r\n> \r\n> What kind of workload is it? How many connections? Are you running blocking operations on EventLoop?\r\n\r\n5 connections only,no blocking operations on EventLoop", "the cause i already found\r\n\r\n\"nioEventLoopGroup-3-1\" Id=14 cpuUsage=79.15% deltaTime=171ms time=9015ms RUNNABLE\r\n at io.netty.handler.codec.DelimiterBasedFrameDecoder.indexOf(DelimiterBasedFrameDecoder.java:314)\r\n at io.netty.handler.codec.DelimiterBasedFrameDecoder.decode(DelimiterBasedFrameDecoder.java:236)\r\n at io.netty.handler.codec.DelimiterBasedFrameDecoder.decode(DelimiterBasedFrameDecoder.java:214)\r\n at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501)\r\n at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440)\r\n at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)\r\n at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)\r\n at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)\r\n at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)\r\n at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)\r\n at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)\r\n at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)\r\n at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)\r\n at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)\r\n at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n at java.lang.Thread.run(Thread.java:748)\r\n", "I put up a PR to use a faster search algorithm, but `DelimiterBasedFrameDecoder` is _always_ going to be CPU intensive because it has to search for the delimiters no matter what." ]
[]
"2023-06-15T17:25:21Z"
[]
the cpu usage is too high(80%) when run netty server thread named NioEventLoopGroup-3-1
### Expected behavior ### Actual behavior ### Steps to reproduce ### Minimal yet complete reproducer code (or URL to code) int processors = Runtime.getRuntime().availableProcessors(); EventLoopGroup bossGroup = new NioEventLoopGroup(processors*2); EventLoopGroup workerGroup = new NioEventLoopGroup(processors*2); ### Netty version <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> [<version>4.1.90.Final</version>] </dependency> ### JVM version (e.g. `java -version`) jdk1.8.0_361 ### OS version (e.g. `uname -a`) Windows Server 2022 Datacenter ### some picture is worth a thousand words. [picture1](https://raw.githubusercontent.com/zzy444626905/images/main/netty-bug/1.jpg) [picture2](https://raw.githubusercontent.com/zzy444626905/images/main/netty-bug/2.jpg)
[ "codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java b/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java index 0dea8857765..68197365602 100644 --- a/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java @@ -18,6 +18,7 @@ import static io.netty.util.internal.ObjectUtil.checkPositive; import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.util.internal.ObjectUtil; @@ -311,27 +312,11 @@ private void fail(long frameLength) { * found in the haystack. */ private static int indexOf(ByteBuf haystack, ByteBuf needle) { - for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) { - int haystackIndex = i; - int needleIndex; - for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) { - if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) { - break; - } else { - haystackIndex ++; - if (haystackIndex == haystack.writerIndex() && - needleIndex != needle.capacity() - 1) { - return -1; - } - } - } - - if (needleIndex == needle.capacity()) { - // Found the needle from the haystack! - return i - haystack.readerIndex(); - } + int index = ByteBufUtil.indexOf(needle, haystack); + if (index == -1) { + return -1; } - return -1; + return index - haystack.readerIndex(); } private static void validateDelimiter(ByteBuf delimiter) {
null
train
test
"2023-06-14T14:10:36"
"2023-03-31T03:22:05Z"
zzy444626905
val
netty/netty/13321_13451
netty/netty
netty/netty/13321
netty/netty/13451
[ "keyword_issue_to_pr" ]
22bf43b03999f40459c61b61c453e0989563cc98
dd2c2bbb723c9a10e3efc6d7bc2cc4a4720375e2
[ "You can use `ByteBufUtil.indexOf` to implement a faster `DelimiterBasedFrameDecoder.indexOf`, if you're up for doing a PR. There's some finicky behavior that needs to be preserved, though.", "your delimiter is a single char one @zzy444626905 ? if yes, it shouldn't be that cost if you use a recent enough version of Netty (when https://github.com/netty/netty/pull/10737 was in).", "This was fixed by #13451" ]
[]
"2023-06-15T17:25:21Z"
[]
netty cpu usage is too high when use DelimiterBasedFrameDecoder
"nioEventLoopGroup-3-1" Id=14 cpuUsage=79.15% deltaTime=171ms time=9015ms RUNNABLE at io.netty.handler.codec.DelimiterBasedFrameDecoder.indexOf(DelimiterBasedFrameDecoder.java:314) at io.netty.handler.codec.DelimiterBasedFrameDecoder.decode(DelimiterBasedFrameDecoder.java:236) at io.netty.handler.codec.DelimiterBasedFrameDecoder.decode(DelimiterBasedFrameDecoder.java:214) at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:501) at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:440) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) ### 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/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java" ]
[ "codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java" ]
[]
diff --git a/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java b/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java index 0dea8857765..68197365602 100644 --- a/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java +++ b/codec/src/main/java/io/netty/handler/codec/DelimiterBasedFrameDecoder.java @@ -18,6 +18,7 @@ import static io.netty.util.internal.ObjectUtil.checkPositive; import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.util.internal.ObjectUtil; @@ -311,27 +312,11 @@ private void fail(long frameLength) { * found in the haystack. */ private static int indexOf(ByteBuf haystack, ByteBuf needle) { - for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) { - int haystackIndex = i; - int needleIndex; - for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) { - if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) { - break; - } else { - haystackIndex ++; - if (haystackIndex == haystack.writerIndex() && - needleIndex != needle.capacity() - 1) { - return -1; - } - } - } - - if (needleIndex == needle.capacity()) { - // Found the needle from the haystack! - return i - haystack.readerIndex(); - } + int index = ByteBufUtil.indexOf(needle, haystack); + if (index == -1) { + return -1; } - return -1; + return index - haystack.readerIndex(); } private static void validateDelimiter(ByteBuf delimiter) {
null
val
test
"2023-06-14T14:10:36"
"2023-04-07T00:58:13Z"
zzy444626905
val
netty/netty/13328_13452
netty/netty
netty/netty/13328
netty/netty/13452
[ "keyword_pr_to_issue" ]
bf8e77974c4e470be002415ea04ca567ded6d9b7
26a7df3e9a5a4945786a736ad28cb2db62015016
[ "Good find, we'll take a look." ]
[ "should we use `array[i].equals(o)` ?", "imho this would be \"safer\". ", "Changed it to `Objects.equals` in line with the API spec recommendation – it handles `null` values correctly.", "Oh no, that's not available in the older Java versions. Fine." ]
"2023-06-15T18:49:43Z"
[]
Possible issues with SelectedSelectionKeySet in non-linux operating systems
`SelectedSelectionKeySet` doesn't implement `contains()` method. Or at least it returns always false. This may create issues in non-linux operating systems. To give you more context, in my work, like you do, we try to not produce garbage by replacing `HashSet` with something similar to `SelectedSelectionKeySet`. Actually this trick is something we learned from netty. So while investigating a recent bug, I realized lack of correct implementation of `contains()` method creates problems in macos (and very possibly windows as well). I tried to summarize my finding in here: https://github.com/hazelcast/hazelcast/pull/24267 I do think this issue effects netty as well.
[ "transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java" ]
[ "transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java" ]
[ "transport/src/test/java/io/netty/channel/nio/SelectedSelectionKeySetTest.java" ]
diff --git a/transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java b/transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java index 7117b06029e..b9c72b635cd 100644 --- a/transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java +++ b/transport/src/main/java/io/netty/channel/nio/SelectedSelectionKeySet.java @@ -20,6 +20,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; +import java.util.Objects; final class SelectedSelectionKeySet extends AbstractSet<SelectionKey> { @@ -51,6 +52,13 @@ public boolean remove(Object o) { @Override public boolean contains(Object o) { + SelectionKey[] array = keys; + for (int i = 0, s = size; i < s; i++) { + SelectionKey k = array[i]; + if (k.equals(o)) { + return true; + } + } return false; }
diff --git a/transport/src/test/java/io/netty/channel/nio/SelectedSelectionKeySetTest.java b/transport/src/test/java/io/netty/channel/nio/SelectedSelectionKeySetTest.java index 46dde8b575d..9f5bb2c23db 100644 --- a/transport/src/test/java/io/netty/channel/nio/SelectedSelectionKeySetTest.java +++ b/transport/src/test/java/io/netty/channel/nio/SelectedSelectionKeySetTest.java @@ -102,8 +102,8 @@ public void contains() { SelectedSelectionKeySet set = new SelectedSelectionKeySet(); assertTrue(set.add(mockKey)); assertTrue(set.add(mockKey2)); - assertFalse(set.contains(mockKey)); - assertFalse(set.contains(mockKey2)); + assertTrue(set.contains(mockKey)); + assertTrue(set.contains(mockKey2)); assertFalse(set.contains(mockKey3)); }
val
test
"2023-06-15T21:41:12"
"2023-04-13T14:07:54Z"
ramizdundar
val
netty/netty/13536_13539
netty/netty
netty/netty/13536
netty/netty/13539
[ "keyword_pr_to_issue" ]
64c898307de06a49f365093bb823bd4b7966c3d3
a02644415681e6efc233ff77540003a48908dbf4
[]
[ "can you add a comment to explain where these values come from ?", "Does this mean Java < 8 are not supported?", "@hyperxpro good point... maybe we should just add a version check as well. Let me do this " ]
"2023-08-09T01:22:31Z"
[]
Add support for password-based encryption scheme 2 params (PBES2)
### Expected behavior no exception ### Actual behavior ``` Caused by: java.security.NoSuchAlgorithmException: 1.2.840.113549.1.5.13 SecretKeyFactory not available at javax.crypto.SecretKeyFactory.<init>(SecretKeyFactory.java:122) at javax.crypto.SecretKeyFactory.getInstance(SecretKeyFactory.java:160) at io.netty.handler.ssl.SslContext.generateKeySpec(SslContext.java:1084) at io.netty.handler.ssl.SslContext.getPrivateKeyFromByteBuffer(SslContext.java:1170) at io.netty.handler.ssl.SslContext.toPrivateKey(SslContext.java:1133) at io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:384) ... 2 more ``` ### Steps to reproduce - generate key and certificate ``` openssl genrsa -out rsa.key openssl req -new -key rsa.key -out rsa.csr openssl x509 -req -days 3650 -in rsa.csr -signkey rsa.key -out rsa.crt openssl pkcs8 -topk8 -inform PEM -in rsa.key -outform pem -out rsa_enc_pkcs8.key -v2 aes-256-cbc -passin pass:12345678 -passout pass:12345678 ``` ```java import io.netty.handler.ssl.SslContextBuilder; import java.io.File; public class Test { public static void main(String[] args) { File keyCertChainFile = new File("rsa.crt"); File keyFile = new File("rsa_enc_pkcs8.key"); String password = "12345678"; SslContextBuilder.forServer(keyCertChainFile, keyFile, password); } } ``` For more detailed information,please refer to https://bz.apache.org/bugzilla/show_bug.cgi?id=65767 ### Minimal yet complete reproducer code (or URL to code) ### Netty version 4.1.x ### JVM version (e.g. `java -version`) jdk8u342 ### OS version (e.g. `uname -a`)
[ "handler/src/main/java/io/netty/handler/ssl/SslContext.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/SslContext.java" ]
[ "handler/src/test/java/io/netty/handler/ssl/SslContextTest.java", "handler/src/test/resources/io/netty/handler/ssl/generate-certs.sh", "handler/src/test/resources/io/netty/handler/ssl/rsa_pbes2_enc_pkcs8.key" ]
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslContext.java b/handler/src/main/java/io/netty/handler/ssl/SslContext.java index dc898915da7..a74b18a693c 100644 --- a/handler/src/main/java/io/netty/handler/ssl/SslContext.java +++ b/handler/src/main/java/io/netty/handler/ssl/SslContext.java @@ -27,6 +27,7 @@ import io.netty.util.AttributeMap; import io.netty.util.DefaultAttributeMap; import io.netty.util.internal.EmptyArrays; +import io.netty.util.internal.PlatformDependent; import java.io.BufferedInputStream; import java.security.Provider; @@ -48,6 +49,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyException; @@ -102,6 +104,8 @@ public abstract class SslContext { private final boolean startTls; private final AttributeMap attributes = new DefaultAttributeMap(); + private static final String OID_PKCS5_PBES2 = "1.2.840.113549.1.5.13"; + private static final String PBES2 = "PBES2"; /** * Returns the default server-side implementation provider currently in use. @@ -1081,16 +1085,39 @@ protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key); - SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); + String pbeAlgorithm = getPBEAlgorithm(encryptedPrivateKeyInfo); + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(pbeAlgorithm); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); - Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); + Cipher cipher = Cipher.getInstance(pbeAlgorithm); cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); } + private static String getPBEAlgorithm(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) { + AlgorithmParameters parameters = encryptedPrivateKeyInfo.getAlgParameters(); + String algName = encryptedPrivateKeyInfo.getAlgName(); + // Java 8 ~ 16 returns OID_PKCS5_PBES2 + // Java 17+ returns PBES2 + if (PlatformDependent.javaVersion() >= 8 && parameters != null && + (OID_PKCS5_PBES2.equals(algName) || PBES2.equals(algName))) { + /* + * This should be "PBEWith<prf>And<encryption>". + * Relying on the toString() implementation is potentially + * fragile but acceptable in this case since the JRE depends on + * the toString() implementation as well. + * In the future, if necessary, we can parse the value of + * parameters.getEncoded() but the associated complexity and + * unlikeliness of the JRE implementation changing means that + * Tomcat will use to toString() approach for now. + */ + return parameters.toString(); + } + return encryptedPrivateKeyInfo.getAlgName(); + } + /** * Generates a new {@link KeyStore}. * @@ -1118,12 +1145,19 @@ protected static PrivateKey toPrivateKey(File keyFile, String keyPassword) throw NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { + return toPrivateKey(keyFile, keyPassword, true); + } + + static PrivateKey toPrivateKey(File keyFile, String keyPassword, boolean tryBouncyCastle) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, + InvalidAlgorithmParameterException, + KeyException, IOException { if (keyFile == null) { return null; } // try BC first, if this fail fallback to original key extraction process - if (BouncyCastlePemReader.isAvailable()) { + if (tryBouncyCastle && BouncyCastlePemReader.isAvailable()) { PrivateKey pk = BouncyCastlePemReader.getPrivateKey(keyFile, keyPassword); if (pk != null) { return pk;
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 6f0cfe9eb79..5f43df24e27 100644 --- a/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java +++ b/handler/src/test/java/io/netty/handler/ssl/SslContextTest.java @@ -173,6 +173,13 @@ public void testPkcs8Des3EncryptedRsa() throws Exception { assertNotNull(key); } + @Test + public void testPkcs8Pbes2() throws Exception { + PrivateKey key = SslContext.toPrivateKey(new File(getClass().getResource("rsa_pbes2_enc_pkcs8.key") + .getFile()), "12345678", false); + assertNotNull(key); + } + @Test public void testPkcs1UnencryptedRsaEmptyPassword() throws Exception { assertThrows(IOException.class, new Executable() { diff --git a/handler/src/test/resources/io/netty/handler/ssl/generate-certs.sh b/handler/src/test/resources/io/netty/handler/ssl/generate-certs.sh index 89bf20fa855..ac82cff071c 100755 --- a/handler/src/test/resources/io/netty/handler/ssl/generate-certs.sh +++ b/handler/src/test/resources/io/netty/handler/ssl/generate-certs.sh @@ -71,8 +71,15 @@ openssl gendsa -out dsa_pkcs1_unencrypted.key dsaparam.pem openssl gendsa -des3 -out dsa_pkcs1_des3_encrypted.key -passout pass:example dsaparam.pem openssl gendsa -aes128 -out dsa_pkcs1_aes_encrypted.key -passout pass:example dsaparam.pem +# PBES2 +openssl genrsa -out rsa_pbes2.key +openssl req -new -subj "/CN=NettyTest" -key rsa_pbes2.key -out rsa_pbes2.csr +openssl x509 -req -days 36500 -in rsa_pbes2.csr -signkey rsa_pbes2.key -out rsa_pbes2.crt +openssl pkcs8 -topk8 -inform PEM -in rsa_pbes2.key -outform pem -out rsa_pbes2_enc_pkcs8.key -v2 aes-256-cbc -passin pass:12345678 -passout pass:12345678 + # Clean up intermediate files rm intermediate.csr rm mutual_auth_ca.key mutual_auth_invalid_client.key mutual_auth_client.key mutual_auth_server.key mutual_auth_invalid_intermediate_ca.key mutual_auth_intermediate_ca.key rm mutual_auth_invalid_client.pem mutual_auth_client.pem mutual_auth_server.pem mutual_auth_client_cert_chain.pem mutual_auth_invalid_intermediate_ca.pem mutual_auth_intermediate_ca.pem mutual_auth_invalid_client_cert_chain.pem rm dsaparam.pem +rm rsa_pbes2.crt rsa_pbes2.csr rsa_pbes2.key diff --git a/handler/src/test/resources/io/netty/handler/ssl/rsa_pbes2_enc_pkcs8.key b/handler/src/test/resources/io/netty/handler/ssl/rsa_pbes2_enc_pkcs8.key new file mode 100644 index 00000000000..05e2079fbae --- /dev/null +++ b/handler/src/test/resources/io/netty/handler/ssl/rsa_pbes2_enc_pkcs8.key @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFHzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIJddddGJqvzACAggA +MB0GCWCGSAFlAwQBKgQQ0SIWTVvrPdriTZKRZuWb7QSCBNDoU6Y1qeABJPV726zv +gymMUAZdfxqBlbS865q3RlnHO2xm4082l7VwFK9QGVFIxURx4QU76qjhsoJfmGiv +pAvkZCln90iguY0ssnAzBFi8B2AgBcZrIG1OMQpR0L/hjveIvorg4/vb5rIgyIdn ++3u7I077yF3udPnt0jUYcfonzsOglwa3FVun2yqM7/gAzGkQu/CeOshSQaJ9EV/0 +ZQmemVCJbmm7I2iEq6RUXgBW8hPjo1cwuQznE2jBx3SlhQoSrWTGdy9WXLqwxrHX +e2W6LqaXqFOrgmtPz5h3JzhUh0AGtNS0SsB6AsyKD548NP7NGRlmbUXo8iQXS/Z6 +QmwIh1bt67VecHKka17ZYGBQt/2/zcQddRvlVeT3SbRgGCGQeDnXWhfJIMb6bFDe +vdr0L44zyW6/OwYQU1RNBFclrjtFIAVQEI8L/BVciowsJ7J6W2UsxR3hrLtPjO9o +zH7bp85TlSaSZW3T2HfAPu6isMECzVzZ+x8qnpuDoHjIOZID630Amw1v2/gfFZTA +mXn4gld1JKUBrvBfXN4cjTDC1eO1zvzEZB6VZw6ePhggWijySoLUO+E/mJpP5mNA +4OQSMxNQ+UcZH+MT093cOJeOleOlbc9weIeNhXgONX/pbnq1gV23tN3mZbGIJojY +GZoH32ft76x+DxrMZrjtjL7dOUL5QjjUlpJ6319aaLFf6Z/AIWXBOyHC1i9l+lKv +2hpZ/YS+eyExy/axwx0J4eH+7csDrz63F1A9hRrIxx2wKdYjsKWR21Hb/mst/U4z +1MGWeIX1hqAe7VYUiZBZldnOYdmNG/sRtcHMrW9zqkJUuW25YjuGm9gVbIVw/YOY +lOd/9puSiRzuJLX02p1o1PN17+5rzMkpE4bVpd6Pvbex+oMSUVvd+V845bCB0qCt +eA5TUBi2gbLvj7TqoA+C0zoXGtXD1Ea/7hnmwC5Gzl4m6YmvZRpxXA6Mzs62CYgt +KWJSiuuTfSop/2B8+nnkZQAGKxvXkpFLXyGXfP+Y22X00BB43GtMB2ZPzmliQ+TA +bFePkPBoXqytJR9vrbWJIIzcxaYWTwqN1vZJzIgdFjK2yOiqopGi0sG0zjn8xryv +ZqraVnTznb5xUGojezIbtWwMNIRrmNU9b1HMtpMsnuNNPQy/UhgDqgM6bQOh23Q8 +7DQRqXGlNqJc22ne1E/gN5IxdbrgoE6jnnoAzOlFRD1XdhLBW3hb2DpzTFAveDKi +ti5UHucXrURILD1ee9CtyKcYQajr3XNp0tMJJQFCybnX+zOgH6HXsrfXFT8CghDt +aeo7TBfhVC4MadvggLNWmyjyGJd7KeDGuiXVDsWr9icesDCUgC/T2Lq58boT70BM +T14pABDOqSylJdL0qWV7m8yZ0fNAkrTB/+2qdi4B632NIQ+ZGRZy5WK09jRUtVm0 ++EZMoX6pAjBQR4RwgbyNTJDIt/tXOopBAoEjRc8qWotlJozc3RkpGBHgT8POZT60 +Jxu3QaE9rJq8kfrO/e5gq7zDy4AK/ck1+aVxfiwM1D7vPvFt0WwztdvEGz3Hjpkv +qtj8ePpDBrBo1ISJqVmTi3pvRz/kuKFYvoYdWq2Wluz1NGZdCETwNYIao1/hfP52 +NydFNZTmdrun22ezf6yVGiCaEw== +-----END ENCRYPTED PRIVATE KEY-----
train
test
"2023-08-18T10:52:19"
"2023-08-08T03:24:15Z"
xiezhaokun
val
netty/netty/13540_13546
netty/netty
netty/netty/13540
netty/netty/13546
[ "keyword_pr_to_issue" ]
6f1646fe3aaa5c53f1f1376e049c71e69030dc40
aa07be47d9d2bbb09b1ca9897575ebc4de6056c0
[ "I have reproduced it and found that the decoded value is **not equal** to the original value whenever the `enableHuffmanEncoding` is true or false. And I found a comment in `HpackEncoder.java`: Only **ASCII** is allowed in http2 headers(https://tools.ietf.org/html/rfc7540#section-8.1.2), so if there exists unexpected characters, unexpected errors may happen. \r\n1. support charset ISO-8859-1 \r\n<img width=\"804\" alt=\"image\" src=\"https://github.com/netty/netty/assets/23135058/56b43e66-f645-4a34-bf2b-9d64fab5c421\">\r\n2. support characters with one byte \r\n<img width=\"517\" alt=\"image\" src=\"https://github.com/netty/netty/assets/23135058/8b4f6d0d-6574-4804-bb31-345278cabf39\">\r\n\r\nIn your case, your headers contains invalid character, which is not in ISO-8859-1 charset or more than one byte.\r\n\r\n\r\n", "Thanks for looking into this @tmyVvit! You're totally right that you're not supposed to use non-US-ASCII chars in the the header values but the interesting bit is that, even if you do, something in the decoder/encoder chain normally does sanitization of the string and replaces characters that are outside of allowed range with `?`. Here is a quick REPL demo:\r\n\r\n```scala\r\n@ val buf = Unpooled.buffer(10000) \r\nbuf: io.netty.buffer.ByteBuf = UnpooledByteBufAllocator$InstrumentedUnpooledUnsafeHeapByteBuf(ridx: 0, widx: 0, cap: 10000)\r\n\r\n@ headers.set(\"some-key\", \"hello 우리는에서문제를발견했습니다world\") \r\nres14: io.netty.handler.codec.http2.Http2Headers = DefaultHttp2Headers[some-key: hello 우리는에서문제를발견했습니다world]\r\n\r\n@ encoder.encodeHeaders(1, headers, buf) \r\n\r\n\r\n@ val decodedHeader = decoder.decodeHeaders(1, buf) \r\ndecodedHeader: io.netty.handler.codec.http2.Http2Headers = DefaultHttp2Headers[some-key: hello ??????????????world, some-key: hello ??????????????world]\r\n\r\n@ val decodedHeaderValue = decodedHeader.get(\"some-key\") \r\ndecodedHeaderValue: CharSequence = hello ??????????????world\r\n```\r\n\r\nSomething in that chain is obviously not doing the sanitization right when a) Huffman encoding is ON and b) the string contains certain UTF-8 chars in the certain positions.", "@tmyVvit is right: it's the `一` char at index 195 that is turning onto a `0x0`. The only reason it doesn't turn into a `0x0` when not using huffman encoding is because of the `.getBytes(IO_8859_1)` call instead of doing what huffman encoding does and doing a simple truncation via `string.charAt(i) & 0xFF`. Despite not being a `0x0`, it's a certainty that the resulting value is still not what you wanted.\r\n\r\n@vkostyukov, can you provide a complete example? I'm not getting the same results as you. It may depend on how the `DefaultHttp2Headers` is instantiated. Specifically, when I run\r\n```\r\nHttp2Headers headers = new DefaultHttp2Headers(true, true, 16);\r\nheaders.set(\"some-key\", \"hello 우리는에서문제를발견했습니다world\");\r\n\r\nDefaultHttp2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder();\r\nByteBuf buf = Unpooled.buffer(10000);\r\nencoder.encodeHeaders(1, headers, buf);\r\n\r\nHttp2HeadersDecoder decoder = new DefaultHttp2HeadersDecoder();\r\nHttp2Headers decodedHeader = decoder.decodeHeaders(1, buf);\r\nthrow new Exception(\"Value:\" + decodedHeader.get(\"some-key\"));\r\n// results in java.lang.Exception: Value:hello °¬”Ð\u001c8\u001c|\u001c¬ˆµÈäworld\r\n```\r\n\r\nWhat you all but certainly want is eager validation when the header is added. Unfortunately, and it doesn't seem to be what you're seeing with the '?'s, but it does look like the default validation is broken [here](https://github.com/netty/netty/blob/4.1/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaderValidationUtil.java#L143), specifically chars wider than 1 byte will all be considered 'ok' which is wrong.", "re: https://github.com/netty/netty/issues/13540#issuecomment-1671799091\r\n\r\n@tmyVvit @bryce-anderson what I find a bit confusing in the comment referenced above - https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2 says\r\n\r\n> header **field names** are strings of ASCII\r\n\r\nwhich covers header names, but it doesn't say anything about header **field values**, which sidetracked us into thinking that field values with non-US-ASCII chars are not illegal, and there's a bug in the `HpackEncoder.java`. would it make sense to update the comment in the `HpackEncoder.java` to clarify that and add more context? after re-reading the spec - think it's covered by https://datatracker.ietf.org/doc/html/rfc7540#section-10.3 which points to the \"field-content\" ABNF rule in https://datatracker.ietf.org/doc/html/rfc7230#section-3.2, and https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4 which says:\r\n\r\n> Newly defined header fields SHOULD limit their field values to\r\n US-ASCII octets. A recipient SHOULD treat other octets in field\r\n content (obs-text) as opaque data\r\n\r\nI think some clarification would be helpful for posterity.", "It actually looks like [this code path](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java#L308C17-L310C71) (when Huffman encoding is bypassed) works in our favor, if you will.\r\n\r\n```java\r\n// Only ASCII is allowed in http2 headers, so its fine to use this.\r\n// https://tools.ietf.org/html/rfc7540#section-8.1.2\r\nout.writeCharSequence(string, CharsetUtil.ISO_8859_1);\r\n```\r\n\r\nThis end up calling into `ByteBufUtil.writeAscii` [here](https://github.com/netty/netty/blob/4.1/buffer/src/main/java/io/netty/buffer/AbstractByteBuf.java#L717), which performs sanitization with the `?` character [here](https://github.com/netty/netty/blob/4.1/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java#L1222-L1229). Relevant function is `AsciiString.c2b`\r\n\r\n```java\r\npublic static byte c2b(char c) {\r\n return (byte) ((c > MAX_CHAR_VALUE) ? '?' : c);\r\n}\r\n```\r\n\r\nPerhaps we should re-use the same conversion function in `HpackHuffmanEncoder` [here](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java#L90) (instead of `data.charAt(i) & 0xFF`) to make sanitization behavior consistent whether or not Huffman encoding is engaged. ", "> which performs sanitization with the ? character [here](https://github.com/netty/netty/blob/4.1/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java#L1222-L1229)\r\n\r\n+1 to perform sanitization over making non-US-ASCII characters [prohibited](https://github.com/netty/netty/blob/7127e6074c2f4b965305738d7756d196729b493e/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java#L91-L92) - IMO that may break Netty users who happened to put non-US-ASCII chars in the header values without hitting this issue. if there's insufficient test coverage - making chars prohibited will start failing their requests at runtime causing outages. sanitizing them seems less damaging. as a precedent - Jetty sanitizes non-US-ASCII chars by replacing them with spaces ([ref](https://github.com/eclipse/jetty.project/blob/ad0b5cfa1533e83814c74063b6c2e17b099e5796/jetty-http/src/main/java/org/eclipse/jetty/http/HttpGenerator.java#L894-L906)). given that spec uses \"SHOULD\" when suggesting to restricting chars in field values to US-ASCII octets - I think it may be a reasonable option to sanitize and limit prohibited chars validations to the chars which are prohibited for security reasons https://datatracker.ietf.org/doc/html/rfc7540#section-10.3.", "> Perhaps we should re-use the same conversion function in HpackHuffmanEncoder [here](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java#L90) (instead of data.charAt(i) & 0xFF) to make sanitization behavior consistent whether or not Huffman encoding is engaged.\r\n\r\nI think that makes sense, [here](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java#L136) would also need to be fixed. Would one of you be interested in putting up a PR?\r\n\r\n> +1 to perform sanitization over making non-US-ASCII characters [prohibited](https://github.com/netty/netty/blob/7127e6074c2f4b965305738d7756d196729b493e/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2Headers.java#L91-L92) - IMO that may break Netty users who happened to put non-US-ASCII chars in the header values without hitting this issue.\r\n\r\nThese are not mutually exclusive: the validation is optional (and disabled by default) and happens on header insertion which is a nice feature since it lets you figure out what code is adding illegal headers so you can fix you app. If we don't fix the validation the feature will remain forever broken.", ">I think that makes sense, [here](https://github.com/netty/netty/blob/4.1/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java#L136) would also need to be fixed. Would one of you be interested in putting up a PR?\r\n\r\nI will give it a shot (putting up a PR)! @bryce-anderson @vkostyukov " ]
[ "We cannot directly use `AsciiString.c2b(...)` here because this function does 2 things:\r\n\r\n1. Sanitize the given input char.\r\n2. Cast the sanitized char to a `byte`.\r\n\r\nThen we cast the returned `byte` to `int b`. Overall, we are doing `sanitizedChar.toByte.toInt` and it could yield negative value which cannot be used as array index. For example `128.toByte.toInt == -128`.\r\n\r\nWe can also consider doing:\r\n```java\r\nint b = (char) AsciiString.c2b(data.charAt(i));\r\n```\r\nor \r\n```java\r\nint b = AsciiString.b2c(AsciiString.c2b(data.charAt(i)));\r\n```\r\n\r\nBut it does not seem to be expressive and clear on our intention and it seems awkward IMO.\r\n\r\nSo, I decided to create this `sanitizeChar` local function.", "Updated it to `AsciiString.c2b(data.charAt(i)) & 0xFF` as `0xFF` can produce unsigned int which is what we want here.", "`it's`?", "My understanding of the small value is that it wont sanitize anything since it will never yield a value greater than 255, making it not a very interesting test. The 300 case should cover what we're really interested in wrt ensuring we don't get wrap-around values of null etc.\r\nA second type of test is that would be valuable is that we should get the same result whether we perform the Huffman encoding or not. What if we just test the size 300 and test it twice: once with the encoded set to 512 (the default I believe) and once super short such to force Huffman encoding, then make sure they both yield the same results?", "Thanks Bryce for the suggestion. I think it's a good idea and I have updated this PR with this idea implemented. PTAL.", "looks good." ]
"2023-08-13T06:41:56Z"
[]
Unexpected characters are synthesized by DefaultHttp2HeadersDecoder when Huffman encoding is enabled in HpackEncoder
### What happened? 1. Create a header `DefaultHttp2Headers` with a certain value that exceeds certain size and contain non-ASCII characters, 2. Encode the header using `DefaultHttp2HeadersEncoder`. 3. Decode the encoded header using `DefaultHttp2HeadersDecoder`. 4. If Huffman encoding is enabled in the `HpackDecoder` (used inside `DefaultHttp2HeadersDecoder`), unexpected character(s) magically show up in the decoded string. "Unexpected characters" means: 1. They are not in the original header value which is encoded. 2. Their unicode code points are smaller than 32. Please note that different header value input can yield different unexpected characters. In the below repro code, `NULL (U+0000)` is the unexpected character. We also have header value (which contains company-specific information) that would yield `\r` as unexpected characters. IMO the first thing is to confirm that there is indeed a bug in the HPACK implementation (and/or any other components). ### Steps to reproduce Please refer to the below code. ### Minimal yet complete reproducer code (or URL to code) ```scala test("NULL character is magically synthesized by DefaultHttp2HeadersDecoder when Huffman encoding is enabled in HpackEncoder") { import io.netty.handler.codec.http2.DefaultHttp2Headers import io.netty.handler.codec.http2.DefaultHttp2HeadersEncoder import io.netty.buffer.Unpooled import io.netty.handler.codec.http2.DefaultHttp2HeadersDecoder val headers = new DefaultHttp2Headers val badHeaderValue = "{\"xxxx\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"xxxxxxx\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"xxxx\":\"x\",\"xxxxxxx\":\"xxxxxxxxxxxxxxxxxxxxxxxxxx\",\"xxxxxxxxxxxxxx\":\"我们在Netty中发现了一个bug_ми знайшли проблему в_123мынашлипроблемув_우리는에서문제를발견했습니다Saturday10311031UsersVlad@Alex_ver10311031Sharedで問題が見つかりましたIAPKI_ActivityVlad@Alex우리는에서문제를발견했습니다BatchWeFound_10311031UsersVlad@Alex_ver10311031Shared\",\"xxxxxx\":\"xxxxxxxx\",\"xxxxxxxx\":\"xxxxxx-87\",\"xxxxxxxxx\":\"xxxxxx.xxxxxx.xxxxxx.xxxxxx.24hgjbu2g2hgwoejf231Xxxxxxx/Xxxx\"}" headers.set("some-key", badHeaderValue) val neverSensitive: SensitivityDetector = new SensitivityDetector() { override def isSensitive(name: CharSequence, value: CharSequence) = false } val enableHuffmanEncoding = true // Use the below threshold to control whether Huffman encoding is enabled for the above header value at runtime. val huffCodeThreshold: Int = if (enableHuffmanEncoding) 512 else 51200 val encoder = new DefaultHttp2HeadersEncoder( neverSensitive, false, // ignoreMaxHeaderListSize, same value as default. 64, // dynamicTableArraySizeHint, same value as default. huffCodeThreshold ) val buf = Unpooled.buffer(10000) encoder.encodeHeaders(1, headers, buf) val decoder = new DefaultHttp2HeadersDecoder() val decodedHeader = decoder.decodeHeaders(1, buf) val decodedHeaderValue: String = decodedHeader.get("some-key").toString val nullChar: Char = 0.toChar assert(!badHeaderValue.contains(nullChar)) // `Null` is not in the original header value. if (enableHuffmanEncoding) { // 👇👇👇 Unexpected 'Null' character gets synthesized in the header value 🫢 assert(decodedHeaderValue.contains(nullChar)) } else { // Huffman encoding is disabled. assert(!decodedHeaderValue.contains(nullChar)) } val scalaVersion: String = scala.util.Properties.scalaPropOrElse("version.number", "unknown") println(s"Scala version: $scalaVersion") // 2.12.15 val javaVersion: String = System.getProperty("java.version") println(s"Java version number: $javaVersion") // 11.0.10 val javaVendor: String = System.getProperty("java.vendor") println(s"Java vendor: $javaVendor") // Azul Systems, Inc } ``` ### Netty version `4.1.86.Final` ### JVM version (e.g. `java -version`) ``` Scala version: 2.12.15 Java version number: 11.0.10 Java vendor: Azul Systems, Inc ```
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackEncoder.java", "codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackEncoderTest.java", "codec-http2/src/test/java/io/netty/handler/codec/http2/HpackHuffmanTest.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 322898f94a1..8f2d5a4df9f 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 @@ -305,7 +305,7 @@ private void encodeStringLiteral(ByteBuf out, CharSequence string) { AsciiString asciiString = (AsciiString) string; out.writeBytes(asciiString.array(), asciiString.arrayOffset(), asciiString.length()); } else { - // Only ASCII is allowed in http2 headers, so its fine to use this. + // Only ASCII is allowed in http2 headers, so it is fine to use this. // https://tools.ietf.org/html/rfc7540#section-8.1.2 out.writeCharSequence(string, CharsetUtil.ISO_8859_1); } diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java index c794ade385e..d3641ce98df 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/HpackHuffmanEncoder.java @@ -87,7 +87,7 @@ private void encodeSlowPath(ByteBuf out, CharSequence data) { int n = 0; for (int i = 0; i < data.length(); i++) { - int b = data.charAt(i) & 0xFF; + int b = AsciiString.c2b(data.charAt(i)) & 0xFF; int code = codes[b]; int nbits = lengths[b]; @@ -133,7 +133,7 @@ int getEncodedLength(CharSequence data) { private int getEncodedLengthSlowPath(CharSequence data) { long len = 0; for (int i = 0; i < data.length(); i++) { - len += lengths[data.charAt(i) & 0xFF]; + len += lengths[AsciiString.c2b(data.charAt(i)) & 0xFF]; } return (int) (len + 7 >> 3); }
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 b5f5d6879b8..2a54fbfab9a 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 @@ -204,6 +204,48 @@ public void testManyHeaderCombinations() throws Http2Exception { } } + @Test + public void testSanitization() throws Http2Exception { + final int headerValueSize = 300; + StringBuilder actualHeaderValueBuilder = new StringBuilder(); + StringBuilder expectedHeaderValueBuilder = new StringBuilder(); + + for (int i = 0; i < headerValueSize; i++) { + actualHeaderValueBuilder.append((char) i); // Use the index as the code point value of the character. + if (i <= 255) { + expectedHeaderValueBuilder.append((char) i); + } else { + expectedHeaderValueBuilder.append('?'); // Expect this character to be sanitized. + } + } + String actualHeaderValue = actualHeaderValueBuilder.toString(); + String expectedHeaderValue = expectedHeaderValueBuilder.toString(); + HpackEncoder encoderWithHuffmanEncoding = + new HpackEncoder(false, 64, 0); // Low Huffman code threshold. + HpackEncoder encoderWithoutHuffmanEncoding = + new HpackEncoder(false, 64, Integer.MAX_VALUE); // High Huffman code threshold. + + // Expect the same decoded header value regardless of whether Huffman encoding is enabled or not. + verifyHeaderValueSanitization(encoderWithHuffmanEncoding, actualHeaderValue, expectedHeaderValue); + verifyHeaderValueSanitization(encoderWithoutHuffmanEncoding, actualHeaderValue, expectedHeaderValue); + } + + private void verifyHeaderValueSanitization( + HpackEncoder encoder, + String actualHeaderValue, + String expectedHeaderValue + ) throws Http2Exception { + + String headerKey = "some-key"; + Http2Headers toBeEncodedHeaders = new DefaultHttp2Headers().add(headerKey, actualHeaderValue); + encoder.encodeHeaders(0, buf, toBeEncodedHeaders, Http2HeadersEncoder.NEVER_SENSITIVE); + DefaultHttp2Headers decodedHeaders = new DefaultHttp2Headers(); + hpackDecoder.decode(0, buf, decodedHeaders, true); + buf.clear(); + String decodedHeaderValue = decodedHeaders.get(headerKey).toString(); + Assertions.assertEquals(expectedHeaderValue, decodedHeaderValue); + } + private void setMaxTableSize(int maxHeaderTableSize) throws Http2Exception { hpackEncoder.setMaxHeaderTableSize(buf, maxHeaderTableSize); hpackDecoder.setMaxHeaderTableSize(maxHeaderTableSize); diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackHuffmanTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackHuffmanTest.java index 2a6ea038aac..8b4bddcf998 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackHuffmanTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/HpackHuffmanTest.java @@ -37,9 +37,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; +import java.util.Arrays; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -162,6 +164,39 @@ public void execute() throws Throwable { }); } + @Test + public void testEncoderSanitizingMultiByteCharacters() throws Http2Exception { + final int inputLen = 500; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < inputLen; i++) { + // Starts with 0x4E01 because certain suboptimal sanitization could cause some problem with this input. + // For example, if a multibyte character C is sanitized by doing (C & OxFF), if C == 0x4E01, then + // (0x4E01 & OxFF) is greater than zero which indicates insufficient sanitization. + sb.append((char) (0x4E01 + i)); + } + HpackHuffmanEncoder encoder = new HpackHuffmanEncoder(); + String toBeEncoded = sb.toString(); + ByteBuf buffer = Unpooled.buffer(); + byte[] bytes; + try { + encoder.encode(buffer, toBeEncoded); + bytes = new byte[buffer.readableBytes()]; + buffer.readBytes(bytes); + } finally { + buffer.release(); // Release as soon as possible. + } + byte[] actualBytes = decode(bytes); + String actualDecoded = new String(actualBytes); + char[] charArray = new char[inputLen]; + Arrays.fill(charArray, '?'); + String expectedDecoded = new String(charArray); + assertEquals( + expectedDecoded, + actualDecoded, + "Expect the decoded string to be sanitized and contains only '?' characters." + ); + } + private static byte[] makeBuf(int ... bytes) { byte[] buf = new byte[bytes.length]; for (int i = 0; i < buf.length; i++) {
val
test
"2023-08-10T19:48:40"
"2023-08-09T07:05:07Z"
Lincong
val
netty/netty/13612_13614
netty/netty
netty/netty/13612
netty/netty/13614
[ "keyword_issue_to_pr" ]
709137e8821e84e98646de7b5b5ac1fd84451041
4e17ab6528d7b18236826b75cf55b0cf61b1a129
[ "@fax4ever the `java.lang.ExceptionInInitializerError`should have a cause set... can you add this one as well ?", "> @fax4ever the `java.lang.ExceptionInInitializerError`should have a cause set... can you add this one as well ?\r\n\r\nDebugging the following seems to be the cause:\r\n\r\n``` bash\r\njava.lang.IllegalArgumentException: cannot use an unresolved DNS server address: fe80::21c:42ff:fe00:18%enp0s5/<unresolved>:5\r\n\r\nio.netty.resolver.dns.DnsServerAddresses.sanitize(DnsServerAddresses.java:175)\r\nio.netty.resolver.dns.DnsServerAddresses.sequential(DnsServerAddresses.java:67)\r\nio.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.putIfAbsent(UnixResolverDnsServerAddressStreamProvider.java:261)\r\nio.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.parse(UnixResolverDnsServerAddressStreamProvider.java:241)\r\nio.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.<init>(UnixResolverDnsServerAddressStreamProvider.java:98)\r\nio.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.<init>(UnixResolverDnsServerAddressStreamProvider.java:133)\r\nio.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.parseSilently(UnixResolverDnsServerAddressStreamProvider.java:72)\r\nio.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder$1.provider(DnsServerAddressStreamProviders.java:151)\r\nio.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder$1.<init>(DnsServerAddressStreamProviders.java:130)\r\nio.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder.<clinit>(DnsServerAddressStreamProviders.java:128)\r\nio.netty.resolver.dns.DnsServerAddressStreamProviders.unixDefault(DnsServerAddressStreamProviders.java:117)\r\nio.netty.resolver.dns.DnsServerAddressStreamProviders.platformDefault(DnsServerAddressStreamProviders.java:113)\r\nio.netty.resolver.dns.DnsNameResolverBuilder.<init>(DnsNameResolverBuilder.java:66)\r\n```\r\n\r\nThanks for the support!", "Maybe the address `fe80::21c:42ff:fe00:18` cannot be resolved?", "@fax4ever should be fixed by https://github.com/netty/netty/pull/13614", "> @fax4ever should be fixed by #13614\r\n\r\nthank you @normanmaurer for the very quick fix!" ]
[ "We can reuse the `addr` variable here, instead of recreating the `InetSocketAddress` object." ]
"2023-09-15T10:33:02Z"
[]
Error parsing IPv6 interface Unix resolv.conf
### Expected behavior I have the following `/etc/resolv.conf`: ``` conf # Generated by NetworkManager search localdomain nameserver 10.211.55.1 nameserver fe80::21c:42ff:fe00:18%enp0s5 ``` if I comment the last line, it works! my network interfaces are: ``` bash [fabio@localhost infinispan]$ ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: enp0s5: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 link/ether 00:1c:42:32:14:87 brd ff:ff:ff:ff:ff:ff inet 10.211.55.25/24 brd 10.211.55.255 scope global dynamic noprefixroute enp0s5 valid_lft 1480sec preferred_lft 1480sec inet6 fdb2:2c26:f4e4:0:21c:42ff:fe32:1487/64 scope global dynamic noprefixroute valid_lft 2591703sec preferred_lft 604503sec inet6 fe80::21c:42ff:fe32:1487/64 scope link noprefixroute valid_lft forever preferred_lft forever 3: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default link/ether 02:42:ec:2a:d3:64 brd ff:ff:ff:ff:ff:ff ``` ### Actual behavior ``` bash java.lang.ExceptionInInitializerError: Exception java.lang.ExceptionInInitializerError [in thread "testng-TracingPropagationTest"] at io.netty.resolver.dns.UnixResolverDnsServerAddressStreamProvider.parseSilently(UnixResolverDnsServerAddressStreamProvider.java:80) at io.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder$1.provider(DnsServerAddressStreamProviders.java:151) at io.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder$1.<init>(DnsServerAddressStreamProviders.java:130) at io.netty.resolver.dns.DnsServerAddressStreamProviders$DefaultProviderHolder.<clinit>(DnsServerAddressStreamProviders.java:128) at io.netty.resolver.dns.DnsServerAddressStreamProviders.unixDefault(DnsServerAddressStreamProviders.java:117) at io.netty.resolver.dns.DnsServerAddressStreamProviders.platformDefault(DnsServerAddressStreamProviders.java:113) at io.netty.resolver.dns.DnsNameResolverBuilder.<init>(DnsNameResolverBuilder.java:66) at org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory.start(ChannelFactory.java:127) ``` ### Steps to reproduce Try to use a similar `/etc/resolv.conf` ### Minimal yet complete reproducer code (or URL to code) DnsNameResolverBuilder builder = new DnsNameResolverBuilder() .channelType(io.netty.channel.epoll.EpollDatagramChannel.class) .ttl(0, 2147483647) .negativeTtl(0); ### Netty version 4.1.94.Final ### JVM version (e.g. `java -version`) openjdk 17.0.7 2023-04-18 LTS OpenJDK Runtime Environment (Red_Hat-17.0.7.0.7-1.el7openjdkportable) (build 17.0.7+7-LTS) OpenJDK 64-Bit Server VM (Red_Hat-17.0.7.0.7-1.el7openjdkportable) (build 17.0.7+7-LTS, mixed mode, sharing) ### OS version (e.g. `uname -a`) Linux localhost.localdomain 5.14.0-284.18.1.el9_2.x86_64 #1 SMP PREEMPT_DYNAMIC Wed May 31 10:39:18 EDT 2023 x86_64 x86_64 x86_64 GNU/Linux
[ "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 33f461b47f2..f8eff1740ed 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 @@ -211,7 +211,14 @@ private static Map<String, DnsServerAddresses> parse(File... etcResolverFiles) t port = Integer.parseInt(maybeIP.substring(i + 1)); maybeIP = maybeIP.substring(0, i); } - addresses.add(SocketUtils.socketAddress(maybeIP, port)); + InetSocketAddress addr = SocketUtils.socketAddress(maybeIP, port); + // Check if the address is resolved and only if this is the case use it. Otherwise just + // ignore it. This is needed to filter out invalid entries, as if for example an ipv6 + // address is used with a scope that represent a network interface that does not exists + // on the host. + if (!addr.isUnresolved()) { + addresses.add(addr); + } } else if (line.startsWith(DOMAIN_ROW_LABEL)) { int i = indexOfNonWhiteSpace(line, DOMAIN_ROW_LABEL.length()); if (i < 0) {
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 index 41411baf751..f00035912ee 100644 --- a/resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java +++ b/resolver-dns/src/test/java/io/netty/resolver/dns/UnixResolverDnsServerAddressStreamProviderTest.java @@ -288,6 +288,18 @@ public void ignoreComments(@TempDir Path tempDir) throws Exception { assertHostNameEquals("127.0.0.2", stream.next()); } + @Test + public void ipv6Nameserver(@TempDir Path tempDir) throws Exception { + File f = buildFile(tempDir, "search localdomain\n" + + "nameserver 10.211.55.1\n" + + "nameserver fe80::21c:42ff:fe00:18%nonexisting\n"); + UnixResolverDnsServerAddressStreamProvider p = + new UnixResolverDnsServerAddressStreamProvider(f, null); + + DnsServerAddressStream stream = p.nameServerAddressStream("somehost"); + assertHostNameEquals("10.211.55.1", stream.next()); + } + private static void assertHostNameEquals(String expectedHostname, InetSocketAddress next) { assertEquals(expectedHostname, next.getHostString(), "unexpected hostname: " + next); }
test
test
"2023-09-18T23:36:35"
"2023-09-15T08:50:37Z"
fax4ever
val
netty/netty/13515_13695
netty/netty
netty/netty/13515
netty/netty/13695
[ "keyword_pr_to_issue" ]
285ba74f899866ddf3e23a6770c954e350245bd7
2241f829e223f1959e8d04f5c8c4c5612d4d0885
[ "Via local builds I was able to isolate the problematic commit: https://github.com/netty/netty/commit/dc69a943c3682fec16845828cb6d8f0554fad61f\r\n\r\nStill not sure what this breaks - we're using standard PEM format like:\r\n\r\n```\r\n-----BEGIN CERTIFICATE-----\r\n<a bunch of base 64>\r\n-----END CERTIFICATE-----\r\n```\r\n\r\nwith none of the newlines this commit seems to address.", "@andrewparmet I guess you can't share the pem file ?", "Unfortunately not. I've been able to narrow it down a bit:\r\n\r\n- Parsing does work on the JVM - this is only an Android issue\r\n- The text returned by [`m.group(0)` here](https://github.com/netty/netty/blob/aa59245955f5121c4230d46c41a4b7f55e0c9ba7/handler/src/main/java/io/netty/handler/ssl/PemReader.java#L92) is simply `BEGIN` - which is not right at all. I'd have a hard time believing it, but is there a difference between the regex implementations on the JVM and Android?", "hmm... sounds like an android bug then... ", "Sure does. Here's a minimal reproducer:\r\n\r\n```kotlin\r\nprivate val CERT_HEADER = Pattern.compile(\"-+BEGIN\\\\s[^-\\\\r\\\\n]*CERTIFICATE[^-\\\\r\\\\n]*-+(?:\\\\s|\\\\r|\\\\n)+\")\r\nprivate val BODY = Pattern.compile(\"[a-z0-9+/=][a-z0-9+/=\\\\r\\\\n]*\", Pattern.CASE_INSENSITIVE)\r\n\r\nclass RegexTest {\r\n @Test\r\n fun regexTest() {\r\n val content =\r\n \"\"\"\r\n |-----BEGIN CERTIFICATE-----\r\n |abcdef\r\n |-----END CERTIFICATE-----\r\n \"\"\".trimMargin()\r\n\r\n val m = CERT_HEADER.matcher(content)\r\n assertTrue(m.find(0))\r\n m.usePattern(BODY)\r\n assertTrue(m.find())\r\n val body = m.group(0)\r\n assertEquals(\"abcdef\\n\", body)\r\n }\r\n}\r\n```\r\n\r\nThis test passes on the JVM (OpenJDK Runtime Environment Corretto-11.0.18.10.1 (build 11.0.18+10-LTS)) and fails on Android 34.", "Filed: https://issuetracker.google.com/issues/293206296 and we'll see what comes back.", "@andrewparmet thanks... keep us posted ", "Hi there,\r\nI have the same issue here. \r\n\r\nI did some research and found that this is probably not an Android issue.\r\nPemReader class uses regex to parse the certificates from the InputStream, but the thing is that regex works differently in JVM and Android Runtime.\r\nhttps://github.com/netty/netty/blob/285ba74f899866ddf3e23a6770c954e350245bd7/handler/src/main/java/io/netty/handler/ssl/PemReader.java#L84C1-L90C14\r\nPemReader expects that after matching the header the matcher moves the cursor to a position after the header and it works this way in JVM but it doesn't in Android and the certificate body is matched starting from the beginning of the string as just \"BEGIN\". And this is why the conversion to an X509 certificate instance fails.\r\n\r\nThis can be fixed by calling the find() method with the next position after the header as a parameter, or by using the BouncyCastle PEMParser as it's done for the private key.\r\n", "@fishb1 if you know how to fix it please open a PR and we will review it ", "You first say:\r\n\r\n> this is probably not an Android issue\r\n\r\nThen you say:\r\n\r\n> regex works differently in JVM and Android Runtime\r\n\r\nTo me this seems like the definition of \"Android issue\" but if you have a workaround that fixes the implementation on Android while not breaking it on the JVM, then to me that seems like only mild debt (when paired with comment to undo the hack and a link to the Android bug that I filed and Google accepted).\r\n\r\nIn any case we've migrated to using binary certificate files instead of text so we're not held hostage by this bug anymore.", "> To me this seems like the definition of \"Android issue\" but if you have a workaround that fixes the implementation on Android while not breaking it on the JVM, then to me that seems like only mild debt (when paired with comment to undo the hack and a link to the Android bug that I filed and Google accepted).\r\n> \r\n\r\nAhhh, I see now! I expected that usePatten() method reset the latest match position but I read the doc for the method again and it said that the position should not be affected. \r\n\r\nThanks for submitting this! \r\n\r\nBut I think a fix needs to be done anyway to make Netty work in older SDKs, even if Google fixes the regex issue in future versions." ]
[]
"2023-11-10T09:00:53Z"
[]
SSL certificate parsing issue when upgrading beyond 4.1.78 on Android
### Expected behavior We're running a gRPC server on Android. We use SSL and have certificates that work until version 4.1.79, and we'd like to be able to continue to use them on more recent versions. Looking for hints to debug why this would suddenly start failing. ### Actual behavior Certificates fail to parse with: ``` org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: java.lang.RuntimeException: error:0c0000a2:ASN.1 encoding routines:OPENSSL_internal:NOT_ENOUGH_DATA ``` ### Steps to reproduce Upgrade Netty. ### Minimal yet complete reproducer code (or URL to code) Unfortunately this is a complex and proprietary project so it's difficult to provide a reproduction. The relevant interactions are between Netty and gRPC version 1.47.0 and conscrypt-android version 2.5.1, and the code is running on Android API 28. If the short diff between 4.1.78 and 4.1.79 is not enough to find a good solution I can try to build a minimum reproducer. I've also tried to use Jitpack to build intermediate commits but I'm having trouble getting those to run on Android. ### Netty version 4.1.79 ### JVM version (e.g. `java -version`) Android API 28. ### OS version (e.g. `uname -a`) Android 9.
[ "handler/src/main/java/io/netty/handler/ssl/PemReader.java" ]
[ "handler/src/main/java/io/netty/handler/ssl/PemReader.java" ]
[]
diff --git a/handler/src/main/java/io/netty/handler/ssl/PemReader.java b/handler/src/main/java/io/netty/handler/ssl/PemReader.java index 0ee79b71457..33328ea672d 100644 --- a/handler/src/main/java/io/netty/handler/ssl/PemReader.java +++ b/handler/src/main/java/io/netty/handler/ssl/PemReader.java @@ -84,14 +84,21 @@ static ByteBuf[] readCertificates(InputStream in) throws CertificateException { if (!m.find(start)) { break; } + + // Here and below it's necessary to save the position as it is reset + // after calling usePattern() on Android due to a bug. + // + // See https://issuetracker.google.com/issues/293206296 + start = m.end(); m.usePattern(BODY); - if (!m.find()) { + if (!m.find(start)) { break; } ByteBuf base64 = Unpooled.copiedBuffer(m.group(0), CharsetUtil.US_ASCII); + start = m.end(); m.usePattern(CERT_FOOTER); - if (!m.find()) { + if (!m.find(start)) { // Certificate is incomplete. break; } @@ -131,19 +138,21 @@ static ByteBuf readPrivateKey(InputStream in) throws KeyException { } catch (IOException e) { throw new KeyException("failed to read key input stream", e); } - + int start = 0; Matcher m = KEY_HEADER.matcher(content); - if (!m.find()) { + if (!m.find(start)) { throw keyNotFoundException(); } + start = m.end(); m.usePattern(BODY); - if (!m.find()) { + if (!m.find(start)) { throw keyNotFoundException(); } ByteBuf base64 = Unpooled.copiedBuffer(m.group(0), CharsetUtil.US_ASCII); + start = m.end(); m.usePattern(KEY_FOOTER); - if (!m.find()) { + if (!m.find(start)) { // Key is incomplete. throw keyNotFoundException(); }
null
test
test
"2023-11-09T09:43:31"
"2023-07-26T02:51:59Z"
andrewparmet
val
netty/netty/13745_13746
netty/netty
netty/netty/13745
netty/netty/13746
[ "keyword_pr_to_issue" ]
427ace4cdd86cce84e467ec0a8a81ca022ed6f72
7700680138f2310a4d9df51cd0805853c8acdd38
[ "I've verified via https://github.com/franz1981/java-puzzles/commit/e083daa22878511c475135b5863b861471e617a6 that thanks to https://github.com/openjdk/jdk/pull/14375 the type check performed at https://github.com/netty/netty/blob/5155482afc57907a1414994ef5aca79b61ac6999/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java#L255 can add a bimorphic guard with at best 2 concrete types before hitting the O(n) slow path type check, ,making this issue less impactful, but still showing that knowing the arity of the type checks receivers and trying reducing it via type peeling off (eg instanceof vs a known hot path concrete type) can help the JIT to have enough \"budget\" for the remaining ones, and make the JIT optimization even more effective." ]
[]
"2023-12-21T14:06:40Z"
[ "improvement" ]
Http 2 type check slow path detected
This is the `MISS` report from a load test running against a HTTP 2 server written in Netty (basically an hello world-like case, really): ``` -------------------------- Miss: -------------------------- 1: io.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator Count: 208210860 Types: io.netty.channel.ChannelProgressivePromise Traces: io.netty.channel.ChannelOutboundBuffer.progress(ChannelOutboundBuffer.java:255) class: io.netty.channel.ChannelProgressivePromise count: 208210860 -------------------------- 2: io.netty.handler.timeout.IdleStateHandler$1 Count: 187763163 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:36) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 95034173 io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:33) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 92728990 -------------------------- 3: io.netty.channel.DelegatingChannelPromiseNotifier Count: 46112141 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:36) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 46112141 -------------------------- 4: io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder$1 Count: 42734531 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.add(DefaultFutureListeners.java:50) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 42734531 -------------------------- 5: io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder$FlowControlledData Count: 42284283 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:33) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 42284283 -------------------------- 6: io.netty.handler.codec.http2.Http2ConnectionHandler$2 Count: 41044039 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:36) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 41044039 -------------------------- 7: io.netty.channel.VoidChannelPromise$1 Count: 40372959 Types: io.netty.util.concurrent.GenericProgressiveFutureListener Traces: io.netty.util.concurrent.DefaultFutureListeners.<init>(DefaultFutureListeners.java:33) class: io.netty.util.concurrent.GenericProgressiveFutureListener count: 40372959 -------------------------- 8: io.netty.buffer.UnpooledSlicedByteBuf Count: 40123310 Types: io.netty.channel.ChannelFutureListener Traces: io.netty.channel.AbstractCoalescingBufferQueue.remove(AbstractCoalescingBufferQueue.java:157) class: io.netty.channel.ChannelFutureListener count: 40123310 -------------------------- 9: io.netty.buffer.PooledUnsafeDirectByteBuf Count: 5541640 Types: io.netty.handler.codec.http2.Http2StreamFrame Traces: io.vertx.core.http.impl.VertxHttp2ConnectionHandler.channelRead(VertxHttp2ConnectionHandler.java:405) class: io.netty.handler.codec.http2.Http2StreamFrame count: 5541640 -------------------------- ``` The report is compatible with Idea stack analyzer, meaning that can be copied & pasted there and just click in the traces which report the line-of-codes, to address the problems. An explanation about what the report is and why is it worthy to fix the issues it reports. As explained by https://github.com/RedHatPerf/type-pollution-agent misusing interfaces type checks can cause scalability problems, but there are other problems which can happen on how OpenJDK handle the "slow-path" of interface type checks ie if a concrete type doesn't implement a specific interface and, in the hot path, the user code perform a type check against it: in this case the JIT perform a O(n) search (using some vectorized instructions for x86, the infamous `prnz scas`) among the interfaces it transitively implements (so called `secondary_supers`) just to find that the type check would fail. This is obviously not as bad as https://bugs.openjdk.org/browse/JDK-8180450 but it still pretty bad, depending how hot the code path is and how many interfaces are implemented. While developing the type pollution agent, I've found this behaviour and reported it to https://ionutbalosin.com/2023/03/jvm-performance-comparison-for-jdk-17/#typecheckbenchmark to better understand if others JIT impl are affected. Sadly, at the moment of filling this issue, I'm not aware if @rwestrel patch at https://github.com/openjdk/jdk/pull/14375 (which should be in JDK 22 AFAIK), save it the day and fix it, but for sure < JDK 22, even in case of monomorphic receivers (even statically proven as monomorphic) the slow type check always happen. The agent has been than enhanced to capture these cases and it should be read/use like this eg ``` -------------------------- Miss: -------------------------- 1: io.netty.handler.codec.http2.Http2CodecUtil$SimpleChannelPromiseAggregator Count: 208210860 Types: io.netty.channel.ChannelProgressivePromise Traces: io.netty.channel.ChannelOutboundBuffer.progress(ChannelOutboundBuffer.java:255) class: io.netty.channel.ChannelProgressivePromise count: 208210860 -------------------------- ``` it means that `SimpleChannelPromiseAggregator` is being tested against `ChannelProgressivePromise` interface +200 M times, while not implementing it at ```java public void progress(long amount) { Entry e = flushedEntry; assert e != null; ChannelPromise p = e.promise; long progress = e.progress + amount; e.progress = progress; assert p != null; final Class<?> promiseClass = p.getClass(); // fast-path to save O(n) ChannelProgressivePromise's type check on OpenJDK if (promiseClass == VoidChannelPromise.class || promiseClass == DefaultChannelPromise.class) { return; } // this is going to save from type pollution due to https://bugs.openjdk.org/browse/JDK-8180450 if (p instanceof DefaultChannelProgressivePromise) { ((DefaultChannelProgressivePromise) p).tryProgress(progress, e.total); } else if (p instanceof ChannelProgressivePromise) { <------- HERE! ((ChannelProgressivePromise) p).tryProgress(progress, e.total); } } ``` at https://github.com/netty/netty/blob/5155482afc57907a1414994ef5aca79b61ac6999/transport/src/main/java/io/netty/channel/ChannelOutboundBuffer.java#L255 And we know that there was already a fix to speedup the O(n) search against `DefaultChannelPromise`'s exact class, which is indeed the type extended by `SimpleChannelPromiseAggregator`. Can we fix it just by changing ```java // fast-path to save O(n) ChannelProgressivePromise's type check on OpenJDK if (promiseClass == VoidChannelPromise.class || promiseClass == DefaultChannelPromise.class) { return; } ``` into ```java // fast-path to save O(n) ChannelProgressivePromise's type check on OpenJDK if (promiseClass == VoidChannelPromise.class || promiseClass instanceof DefaultChannelPromise) { return; } ``` ? Sadly not, because we cannot trust that extending `DefaultChannelPromise` means NOT implementing `ChannelProgressivePromise` (the original change happened at https://github.com/netty/netty/pull/13225) At the same time a check directly against the `SimpleChannelPromiseAggregator` class introduce the dependency of http2 in a core part, which is just not desiderable/possible. So, how to fix it? And, is it worthy? The former got no precise answer: it depends, and i'm opened to suggestions here. The latter is, usually yes, but your mileage may vary: sadly most Java profilers breaks on it, so it's not easy to find it out, till fixing it.
[ "transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java" ]
[ "transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java" ]
[]
diff --git a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java index 20a0ba09f7b..33f3d81d8e1 100644 --- a/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java +++ b/transport/src/main/java/io/netty/channel/AbstractCoalescingBufferQueue.java @@ -154,38 +154,40 @@ public final ByteBuf remove(ByteBufAllocator alloc, int bytes, ChannelPromise ag if (entry == null) { break; } - if (entry instanceof ChannelFutureListener) { - aggregatePromise.addListener((ChannelFutureListener) entry); - continue; - } - - entryBuffer = (ByteBuf) entry; - int bufferBytes = entryBuffer.readableBytes(); - - if (bufferBytes > bytes) { - // Add the buffer back to the queue as we can't consume all of it. - bufAndListenerPairs.addFirst(entryBuffer); - if (bytes > 0) { - // Take a slice of what we can consume and retain it. - entryBuffer = entryBuffer.readRetainedSlice(bytes); - // we end here, so if this is the only buffer to return, skip composing - toReturn = toReturn == null ? entryBuffer - : compose(alloc, toReturn, entryBuffer); - bytes = 0; + // fast-path vs abstract type + if (entry instanceof ByteBuf) { + entryBuffer = (ByteBuf) entry; + int bufferBytes = entryBuffer.readableBytes(); + + if (bufferBytes > bytes) { + // Add the buffer back to the queue as we can't consume all of it. + bufAndListenerPairs.addFirst(entryBuffer); + if (bytes > 0) { + // Take a slice of what we can consume and retain it. + entryBuffer = entryBuffer.readRetainedSlice(bytes); + // we end here, so if this is the only buffer to return, skip composing + toReturn = toReturn == null ? entryBuffer + : compose(alloc, toReturn, entryBuffer); + bytes = 0; + } + break; } - break; - } - bytes -= bufferBytes; - if (toReturn == null) { - // if there are no more bytes in the queue after this, there's no reason to compose - toReturn = bufferBytes == readableBytes - ? entryBuffer - : composeFirst(alloc, entryBuffer); - } else { - toReturn = compose(alloc, toReturn, entryBuffer); + bytes -= bufferBytes; + if (toReturn == null) { + // if there are no more bytes in the queue after this, there's no reason to compose + toReturn = bufferBytes == readableBytes + ? entryBuffer + : composeFirst(alloc, entryBuffer); + } else { + toReturn = compose(alloc, toReturn, entryBuffer); + } + entryBuffer = null; + } else if (entry instanceof DelegatingChannelPromiseNotifier) { + aggregatePromise.addListener((DelegatingChannelPromiseNotifier) entry); + } else if (entry instanceof ChannelFutureListener) { + aggregatePromise.addListener((ChannelFutureListener) entry); } - entryBuffer = null; } } catch (Throwable cause) { safeRelease(entryBuffer);
null
train
test
"2023-12-19T22:05:52"
"2023-12-21T09:13:44Z"
franz1981
val
netty/netty/13740_13769
netty/netty
netty/netty/13740
netty/netty/13769
[ "keyword_pr_to_issue" ]
b1947417b7444326965086b951b75f0128cf7085
6c883d620722c12e19561ce1a10b41fadfbd6a60
[ "We are also facing the same issue.", "We are also facing the same issue" ]
[]
"2024-01-07T17:58:34Z"
[]
Partitioned attribute support in ResponseCookie class
Chrome is going to deprecate third party cookies in near future, and it is mentioned [here](https://developers.google.com/privacy-sandbox/3pcd). We have many integration/leading applications depends on cross site cookies; all those will not work if the third-party cookies are not allowed to use. There are some suggested ways to mitigate cross site issues which depend on cookies. Cookies having independent partitioned state (CHIPS) is one of the proposals(https://developer.chrome.com/docs/privacy-sandbox/chips/). For this, in ResponseCookie need a Boolean attribute called **partitioned** similar to secure field ``` private final boolean partitioned; /** * Add the "Partitioned" attribute to the cookie. */ ResponseCookieBuilder partitioned(boolean partitioned); ``` For testing purposes, we did try extending httpcookie and created custom cookie class but to add that cookie in exchange response, they are expecting only of type ResponseCookie spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpResponse.java - getCookies() and addCookie() We do create the below request https://github.com/spring-projects/spring-framework/issues/31454 Please do provide this support as early as possible, we want to test by disabling third party cookies from leading applications for impact analysis. Thanks in advance.
[ "codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java" ]
[ "codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java", "codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java" ]
[ "codec-http/src/test/java/io/netty/handler/codec/http/cookie/ClientCookieDecoderTest.java", "codec-http/src/test/java/io/netty/handler/codec/http/cookie/ServerCookieEncoderTest.java" ]
diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java index e143b319051..8b967507c28 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ClientCookieDecoder.java @@ -156,6 +156,7 @@ private static class CookieBuilder { private boolean secure; private boolean httpOnly; private SameSite sameSite; + private boolean partitioned; CookieBuilder(DefaultCookie cookie, String header) { this.cookie = cookie; @@ -183,6 +184,7 @@ Cookie cookie() { cookie.setSecure(secure); cookie.setHttpOnly(httpOnly); cookie.setSameSite(sameSite); + cookie.setPartitioned(partitioned); return cookie; } @@ -210,6 +212,8 @@ void appendAttribute(int keyStart, int keyEnd, int valueStart, int valueEnd) { parse7(keyStart, valueStart, valueEnd); } else if (length == 8) { parse8(keyStart, valueStart, valueEnd); + } else if (length == 11) { + parse11(keyStart); } } @@ -252,6 +256,12 @@ private void parse8(int nameStart, int valueStart, int valueEnd) { } } + private void parse11(int nameStart) { + if (header.regionMatches(true, nameStart, CookieHeaderNames.PARTITIONED, 0, 11)) { + partitioned = true; + } + } + private static boolean isValueDefined(int valueStart, int valueEnd) { return valueStart != -1 && valueStart != valueEnd; } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java index 7e3881ebef0..723f3b980fa 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/CookieHeaderNames.java @@ -30,6 +30,8 @@ public final class CookieHeaderNames { public static final String SAMESITE = "SameSite"; + public static final String PARTITIONED = "Partitioned"; + /** * Possible values for the SameSite attribute. * See <a href="https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-05">changes to RFC6265bis</a> diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java index f40a0277d55..41d54ca8e53 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/DefaultCookie.java @@ -36,6 +36,7 @@ public class DefaultCookie implements Cookie { private boolean secure; private boolean httpOnly; private SameSite sameSite; + private boolean partitioned; /** * Creates a new cookie with the specified name and value. @@ -140,6 +141,24 @@ public void setSameSite(SameSite sameSite) { this.sameSite = sameSite; } + /** + * Checks to see if this {@link Cookie} is partitioned + * + * @return True if this {@link Cookie} is partitioned, otherwise false + */ + public boolean isPartitioned() { + return partitioned; + } + + /** + * Sets the {@code Partitioned} attribute of this {@link Cookie} + * + * @param partitioned True if this {@link Cookie} is to be partitioned, otherwise false + */ + public void setPartitioned(boolean partitioned) { + this.partitioned = partitioned; + } + @Override public int hashCode() { return name().hashCode(); @@ -256,6 +275,9 @@ public String toString() { if (sameSite() != null) { buf.append(", SameSite=").append(sameSite()); } + if (isPartitioned()) { + buf.append(", Partitioned"); + } return buf.toString(); } } diff --git a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java index b33d923b2b5..d5153f9eff0 100644 --- a/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java +++ b/codec-http/src/main/java/io/netty/handler/codec/http/cookie/ServerCookieEncoder.java @@ -129,6 +129,9 @@ public String encode(Cookie cookie) { if (c.sameSite() != null) { add(buf, CookieHeaderNames.SAMESITE, c.sameSite().name()); } + if (c.isPartitioned()) { + add(buf, CookieHeaderNames.PARTITIONED); + } } return stripTrailingSeparator(buf);
diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ClientCookieDecoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ClientCookieDecoderTest.java index deb0edbf339..2cf53b59338 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ClientCookieDecoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ClientCookieDecoderTest.java @@ -41,7 +41,7 @@ public class ClientCookieDecoderTest { public void testDecodingSingleCookieV0() { String cookieString = "myCookie=myValue;expires=" + DateFormatter.format(new Date(System.currentTimeMillis() + 50000)) - + ";path=/apathsomewhere;domain=.adomainsomewhere;secure;SameSite=None"; + + ";path=/apathsomewhere;domain=.adomainsomewhere;secure;SameSite=None;Partitioned"; Cookie cookie = ClientCookieDecoder.STRICT.decode(cookieString); assertNotNull(cookie); @@ -55,7 +55,9 @@ public void testDecodingSingleCookieV0() { assertTrue(cookie.isSecure()); assertThat(cookie, is(instanceOf(DefaultCookie.class))); - assertEquals(SameSite.None, ((DefaultCookie) cookie).sameSite()); + DefaultCookie c = (DefaultCookie) cookie; + assertEquals(SameSite.None, c.sameSite()); + assertTrue(c.isPartitioned()); } @Test diff --git a/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ServerCookieEncoderTest.java b/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ServerCookieEncoderTest.java index 6c86f65ff2d..51863f65870 100644 --- a/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ServerCookieEncoderTest.java +++ b/codec-http/src/test/java/io/netty/handler/codec/http/cookie/ServerCookieEncoderTest.java @@ -44,13 +44,14 @@ public void testEncodingSingleCookieV0() throws ParseException { int maxAge = 50; String result = "myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere;" + - " Domain=.adomainsomewhere; Secure; SameSite=Lax"; + " Domain=.adomainsomewhere; Secure; SameSite=Lax; Partitioned"; DefaultCookie cookie = new DefaultCookie("myCookie", "myValue"); cookie.setDomain(".adomainsomewhere"); cookie.setMaxAge(maxAge); cookie.setPath("/apathsomewhere"); cookie.setSecure(true); cookie.setSameSite(SameSite.Lax); + cookie.setPartitioned(true); String encodedCookie = ServerCookieEncoder.STRICT.encode(cookie);
train
test
"2024-01-16T10:02:14"
"2023-12-19T08:47:26Z"
aramired
val
netty/netty/13788_13789
netty/netty
netty/netty/13788
netty/netty/13789
[ "keyword_pr_to_issue" ]
e2c8a9774728c4855191293d0697a03729477f84
b611fdebdf7787c214732991fb9142662f2583eb
[ "Is this issue (https://github.com/grpc/grpc-java/issues/10830) resolved by this PR? ", "@njimenezotto That issue is completely different than this." ]
[ "Does this work correctly if there are two different messages in the `input` ByteBuffer waiting to be processed? In my minds eye it will skip them both.", "I think you're right, if there's more data already buffered it'll skip all of it. I'm trying to think of an alternative but if the length of the payload doesn't match the actual payload not sure how we can skip the correct number of bytes to read the next frame correctly. Maybe adding length checks while cumulating the data in the ByteToMessageDecoder?", "Instead of using a boolean flag we could instead do something like passing `input.readSlice(payloadLength)` into the `processPayloadState` method. That would require us to move the \r\n```\r\nif (input.readableBytes() < payloadLength) {\r\n // Wait until the entire payload has been read.\r\n return;\r\n}\r\n```\r\ncheck up out of the `processPayloadState` method to right before we slice and call it but tbh that feels more readable anyway.\r\n\r\nDoing that has two nice properties and one negative: it's nice because it 'slices' exactly one frame from `input` which (1) makes it hard for `processPayloadState` to corrupt other frames and (2) makes consumption of the frame from `input` happen eagerly so you don't have to worry about skipping bytes on exception. Downside is that it does cost an extra allocation. On balance, I'd happily pay the allocation of the slice wrapper: it isn't a drop in the ocean imo.", "That makes sense to me, but I think we'd hit some issues if the advertised `payloadLength` of the frame doesn't match the actual payload. In the use case I'm looking at, I see two cases where we could see issues\r\n- __Advertised Payload Length greater than payload__: More data skipped than actually included and next frame would not be properly read.\r\n- __Advertised Payload Length less than payload__: Less data skipped than actually included and data will be left over and next frame would not be properly read.", "@isaacrivriv I read description of #13788 to understand expected behavior, but it seems like this is not what RFC wants. [Section 4.2](https://datatracker.ietf.org/doc/html/rfc9113#section-4.2) says:\r\n\r\n> An endpoint MUST send an error code of [FRAME_SIZE_ERROR](https://datatracker.ietf.org/doc/html/rfc9113#FRAME_SIZE_ERROR) if a frame exceeds the size defined in [SETTINGS_MAX_FRAME_SIZE](https://datatracker.ietf.org/doc/html/rfc9113#SETTINGS_MAX_FRAME_SIZE), exceeds any limit defined for the frame type, or is too small to contain mandatory frame data. A frame size error in a frame that could alter the state of the entire connection MUST be treated as a [connection error](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler) ([Section 5.4.1](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler))\r\n\r\n\r\nThen section 5.4.1 describes that the state of the entire connection is expected to be corrupted at that point and we must close it. It's not expected that we could recover and process more frames on the same connection.\r\n\r\nIf we don't already have one, it will be helpful if you could implement an integration test with a full HTTP/2 server and a faked client that send a malformed frame, then assert that the server responds with `FRAME_SIZE_ERROR`, then closes connection. ", "In this case, the behavior I'm seeing with the response from a Netty HTTP2 server matches the RFC specification where in some cases even though a malformed frame comes in, it doesn't actually shut down the connection but just resets a stream and more streams can be accepted after that. [Section 6.3](https://datatracker.ietf.org/doc/html/rfc9113#name-priority) is an example\r\n\r\n> A PRIORITY frame with a length other than 5 octets MUST be treated as a [stream error](https://datatracker.ietf.org/doc/html/rfc9113#StreamErrorHandler) ([Section 5.4.2](https://datatracker.ietf.org/doc/html/rfc9113#StreamErrorHandler)) of type [FRAME_SIZE_ERROR](https://datatracker.ietf.org/doc/html/rfc9113#FRAME_SIZE_ERROR).\r\n\r\nAs it is currently working if I send a priority frame with length 4, I correctly get a reset frame back with a frame size error (which is what the RFC states) but starting another stream with a valid request after that, it is not parsed correctly due to leftover data from the previous request.\r\n\r\nThe error really happens in those cases where the RFC states that a stream reset is used rather than a connection error because when a connection error happens everything gets cleaned up where in a stream reset there could still be leftover data", "The most important part is: \r\n\r\n> A frame size error in a frame that could alter the state of the entire connection MUST be treated as a [connection error](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler) ([Section 5.4.1](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler))\r\n\r\nIt's ok to send `RST_STREAM` frame first. But then, how can we trust the frame if it has incorrect format? If we can not trust it, we don't know how many bytes to skip. It could happen that we received total garbage that just happen to start with \"priority frame header\". So, if we don't know how to continue, we should send GO_AWAY and close connection. ", "The RFC states the following after that statement which confuses me\r\n\r\n> A frame size error in a frame that could alter the state of the entire connection MUST be treated as a [connection error](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler) ([Section 5.4.1](https://datatracker.ietf.org/doc/html/rfc9113#ConnectionErrorHandler)); **this includes any frame carrying a [field block](https://datatracker.ietf.org/doc/html/rfc9113#FieldBlock) ([Section 4.3](https://datatracker.ietf.org/doc/html/rfc9113#FieldBlock)) (that is, [HEADERS](https://datatracker.ietf.org/doc/html/rfc9113#HEADERS), [PUSH_PROMISE](https://datatracker.ietf.org/doc/html/rfc9113#PUSH_PROMISE), and [CONTINUATION](https://datatracker.ietf.org/doc/html/rfc9113#CONTINUATION)), a [SETTINGS](https://datatracker.ietf.org/doc/html/rfc9113#SETTINGS) frame, and any frame with a stream identifier of 0.**\r\n\r\nSo in my head the RFC states the specifics of what \"altering the state of the connection\" is in that sentence which this particular case doesn't seem to apply. By sending a priority frame to a specific stream (not 0) we can hit this issue and doesn't really fall under those categories IMO. \r\n\r\nI think we should skip the bytes if the payload length matches the actual frame payload and send a reset stream which matches the RFC and continue reading for the cases where a stream reset is required. I also agree closing the connection on cases where the payload length doesn't actually match the frame payload considering that we are receiving garbage in those cases but I'm making sure this isn't against the RFC since it states otherwise about keeping the connection active.\r\n\r\nThe other question would be, how would we know if the frame that came in actually matches the payload length? By the time Netty start's parsing H2 data we could have more messages queued in the buffer which we're not aware of. I'm thinking maybe a check on every decode to peek at the payload length and compare to the actual frame length? I'm not aware of a way to cleanly distinguish frames from each other TBH.", "It's convenient to think of the H2 protocol as having (at least) two layers: the framing layer (the first 9 octets of a frame) and then the actual frame payloads themselves which will have some consistency requirements. What I'm suggesting leverages the fact that the length from the framing layer should be authoritative in terms of frame boundaries.\r\nWhat to do if we detect corruption/inconsistencies in the payload (which could be that the payload is short or long, for example) will be case specific and gets into the details of what @idelpivnitskiy pointed to in his suggestions. This is actually a third advantage of what I'm suggestion: too few/extra bytes can signal corruption and if we slice we can detect that. For example, a RST_STREAM frame with size other than 4 octets should be a connection error (end of [6.4](https://datatracker.ietf.org/doc/html/rfc9113#section-6.4)). However in main if we received a RST_STREAM frame of size 5 (as determined by the frame header) where the last byte is meaningless instead of sending a connection error and potentially alerting the peer to a bug in their implementation we'll instead end up with a corrupt framing layer: we won't fail because we don't enforce the size and we won't consume that extra byte from the data stream so it will end up being interpreted as the first byte of the next frames header. In this specific example we could also just read the `payloadLength` field instead of checking that we have a buffer of size 4, but having a sliced buffer ensures decoders don't try to use more data than what the frame was advertised to contain via the header.", "Yeah that's exactly the issue I was seeing, leftover data is parsed as part of the next frame when malformed frames like that are parsed. So with @idelpivnitskiy comments and this thread I'm thinking we can implement the slice mechanism but there needs to be more checks implemented so that the payload length matches the actual payload and for those cases where we don't find a match we can alert by sending a Go Away frame? I'm trying to see what a path forward would be for this.", "See my comment above but the TL;DR is that the length field from the frame header is authoritative on size of a frames payload. What to do if that payload size is too short or too long when decoding the frame is frame type specific and is described as part of the individual frame definitions.", "That sounds right: whether to send a GOAWAY or a RST_STREAM is frame type specific and described as part of the frame definitions (usually at the ends). I don't think you have to implement all those checks as part of this PR if you don't want to: they could be done as a follow up. Finding this and making sure we keep a correct framing layer is already a huge step forward from where we are now.", "Taking a closer look it seems most of them (if not all) already verify the frame length and do the right thing wrt RST vs GOAWAY but its done as part of the `processHeaderState` state so we haven't been able to slice before the exception is thrown, and we may not even have that many bytes available, so we'd need to move the verification to a new method and perform it right before we `processPayloadState(ctx, input.slice(..), ..)`.", "All of these methods still work despite passing in a value with different meaning only because the writer index now matches the payload length. Now that you've sliced the buffer really we don't need to pass in the end length as each method could derive it from the passed in slice itself.", "fwiw, now that you've sliced the buffer I don't think you need to do this re-ordering.", "```suggestion\r\n // Stream error found, reset to reading headers once again for next frame coming in\r\n```", "Some of the verifications result in a stream error, not a connection error. If that happens I think we end up with a corrupt stream. To fix it we can simply move verification to after we've called input.readSlice(..) so that we've consumed the frame from the framing layer. We've already committed to reading frames this large so it doesn't seem like a potential attack vector. The only downside seems to be that for connection errors it can potentially delay closing the session.", "We should be able to simplify the management of this variable: we switch back to `readingHeaders = true` as soon as we consume the frame payload, so we can set it right after we `.readSlice(..)` and before we attempt to verify and process the payload and remove the mutations elsewhere.", "True, I'll update the method signatures to make this cleaner.", "Agree, I forgot that we aren't skipping the bytes anymore like the original solution if this happens. I'll move this verification after slicing", "This makes sense, I'll simplify with this in mind", "I think these can be even simpler: \r\n```suggestion\r\n int dataLength = lengthWithoutTrailingPadding(payload.readableBytes(), padding);\r\n```", "Do you think we could just adjust the writer index on `payload`?", "Agree, I'll make the changes to all of these ", "So instead of slicing the data buffer just move the writer index of the payload to dataLength?", "Yes: I think we sliced the payload previously because we didn't want to leak the parent buffer but since we've already sliced it there shouldn't be any harm in sharing that. At a minimum, I expect padding to be rare so if there isn't any padding to slice out we can certainly just send `payload` along.\r\n\r\nAnd to be more precise, I think we should do `payload.writeIndex(payload.readerIndex() + dataLength)`. `payload.readerIndex()` should always be 0 now, but it will make the code more resilient to future changes.", "Ok cool I'll make that change and saw the payload being further sliced while reading a Go Away frame so I'm updating that as well", "@bryce-anderson @idelpivnitskiy you are happy with what we have now ?", "@normanmaurer, I am. This should prevent frame stream corruption for problems that result in a stream error at the validation phase.\r\n\r\nOne behavior change that I think is worth point out is that we'll now aggregate the data for the next frame before doing any of the per-frame validations other than max frame length. I think this is safe because we've already agreed to accept frames that big such as data and headers frames but it's worth a thought.", "Consider naming it `verifyFrameState` because at the time we invoke this method, we already consumed the whole frame, not just its header. This will also align with other `verify*Frame()` methods it's calling. ", "Consider adding an assertion (ideally with a comment) that `in.readableBytes() == payloadLength`. In case in the future someone invokes this method from an incorrect state, it will rise an error.", "Consider adding a comment for future devs why we read the full header before throwing an excepting on case `payloadLength > maxFrameSize`", "@isaacrivriv thanks for pointing to the continuation of that sentence. That makes sense, for the current case we don't need to close the entire connection. Great catch!", "I agree, renaming it makes more sense I'll make this change", "Sounds good with me, I'll make this change", "I'm looking at this again and since it's a connectionError which closes the connection I don't think we have to read the full headers before throwing the exception so I'm undoing these changes" ]
"2024-01-18T05:02:39Z"
[]
DefaultHttp2FrameReader does not reset after malformed request comes in
### Expected behavior After a request comes in which causes a stream error, (such as a priority frame with an invalid stream dependency or with an invalid payload length) the following frame must be treated as a new frame. ### Actual behavior After such a malformed request comes in, the following frame after the malformed is parsed with leftover data from the previous request. ### Steps to reproduce 1. Start an HTTP2 request. 2. Send a priority request on a stream with an invalid payload length 3. After failed stream send a valid stream request to the HTTP2 session 4. HTTP2 request should work but doesn't As a side effect of this, I see a Go Away being sent by the server with the following message `Frame length: 16711680 exceeds maximum: 16384` ### Minimal yet complete reproducer code (or URL to code) I expanded the HTTP2 client example code for a reproducer. Tested against the HTTP2 Server example https://github.com/netty/netty/compare/4.1...isaacrivriv:netty:test-bad-priority-frame ### Netty version 4.1.105 ### JVM version (e.g. `java -version`) openjdk version "17.0.7" 2023-04-18 IBM Semeru Runtime Open Edition 17.0.7.0 (build 17.0.7+7) Eclipse OpenJ9 VM 17.0.7.0 (build openj9-0.38.0, JRE 17 Mac OS X amd64-64-Bit Compressed References 20230418_450 (JIT enabled, AOT enabled) OpenJ9 - d57d05932 OMR - 855813495 JCL - 9d7a231edbc based on jdk-17.0.7+7) ### OS version (e.g. `uname -a`) Darwin Kernel Version 23.0.0
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java" ]
[ "codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java" ]
[ "codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameReaderTest.java" ]
diff --git a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java index dc0857ec6b8..dae497d9bb5 100644 --- a/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java +++ b/codec-http2/src/main/java/io/netty/handler/codec/http2/DefaultHttp2FrameReader.java @@ -143,24 +143,25 @@ public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListen } try { do { - if (readingHeaders) { - processHeaderState(input); - if (readingHeaders) { - // Wait until the entire header has arrived. - return; - } + if (readingHeaders && !preProcessFrame(input)) { + return; } - // The header is complete, fall into the next case to process the payload. // This is to ensure the proper handling of zero-length payloads. In this // case, we don't want to loop around because there may be no more data // available, causing us to exit the loop. Instead, we just want to perform // the first pass at payload processing now. - processPayloadState(ctx, input, listener); - if (!readingHeaders) { - // Wait until the entire payload has arrived. + // Wait until the entire payload has been read. + if (input.readableBytes() < payloadLength) { return; } + // Slice to work only on the frame being read + ByteBuf framePayload = input.readSlice(payloadLength); + // We have consumed the data for this frame, next time we read, + // we will be expecting to read a new frame header. + readingHeaders = true; + verifyFrameState(); + processPayloadState(ctx, framePayload, listener); } while (input.isReadable()); } catch (Http2Exception e) { readError = !Http2Exception.isStreamError(e); @@ -174,13 +175,13 @@ public void readFrame(ChannelHandlerContext ctx, ByteBuf input, Http2FrameListen } } - private void processHeaderState(ByteBuf in) throws Http2Exception { + private boolean preProcessFrame(ByteBuf in) throws Http2Exception { + // Start pre-processing the frame by reading the necessary data + // in common between all frame types if (in.readableBytes() < FRAME_HEADER_LENGTH) { - // Wait until the entire frame header has been read. - return; + // Wait until the entire framing section has been read. + return false; } - - // Read the header and prepare the unmarshaller to read the frame. payloadLength = in.readUnsignedMedium(); if (payloadLength > maxFrameSize) { throw connectionError(FRAME_SIZE_ERROR, "Frame length: %d exceeds maximum: %d", payloadLength, @@ -189,10 +190,11 @@ private void processHeaderState(ByteBuf in) throws Http2Exception { frameType = in.readByte(); flags = new Http2Flags(in.readUnsignedByte()); streamId = readUnsignedInt(in); - - // We have consumed the data, next time we read we will be expecting to read the frame payload. readingHeaders = false; + return true; + } + private void verifyFrameState() throws Http2Exception { switch (frameType) { case DATA: verifyDataFrame(); @@ -233,24 +235,16 @@ private void processHeaderState(ByteBuf in) throws Http2Exception { private void processPayloadState(ChannelHandlerContext ctx, ByteBuf in, Http2FrameListener listener) throws Http2Exception { - if (in.readableBytes() < payloadLength) { - // Wait until the entire payload has been read. - return; - } - - // Only process up to payloadLength bytes. - int payloadEndIndex = in.readerIndex() + payloadLength; - - // We have consumed the data, next time we read we will be expecting to read a frame header. - readingHeaders = true; - + // When this method is called, we ensure that the payload buffer passed in + // matches what we expect to be reading for payloadLength + assert in.readableBytes() == payloadLength; // Read the payload and fire the frame event to the listener. switch (frameType) { case DATA: - readDataFrame(ctx, in, payloadEndIndex, listener); + readDataFrame(ctx, in, listener); break; case HEADERS: - readHeadersFrame(ctx, in, payloadEndIndex, listener); + readHeadersFrame(ctx, in, listener); break; case PRIORITY: readPriorityFrame(ctx, in, listener); @@ -262,25 +256,24 @@ private void processPayloadState(ChannelHandlerContext ctx, ByteBuf in, Http2Fra readSettingsFrame(ctx, in, listener); break; case PUSH_PROMISE: - readPushPromiseFrame(ctx, in, payloadEndIndex, listener); + readPushPromiseFrame(ctx, in, listener); break; case PING: readPingFrame(ctx, in.readLong(), listener); break; case GO_AWAY: - readGoAwayFrame(ctx, in, payloadEndIndex, listener); + readGoAwayFrame(ctx, in, listener); break; case WINDOW_UPDATE: readWindowUpdateFrame(ctx, in, listener); break; case CONTINUATION: - readContinuationFrame(in, payloadEndIndex, listener); + readContinuationFrame(in, listener); break; default: - readUnknownFrame(ctx, in, payloadEndIndex, listener); + readUnknownFrame(ctx, in, listener); break; } - in.readerIndex(payloadEndIndex); } private void verifyDataFrame() throws Http2Exception { @@ -402,20 +395,20 @@ private void verifyUnknownFrame() throws Http2Exception { verifyNotProcessingHeaders(); } - private void readDataFrame(ChannelHandlerContext ctx, ByteBuf payload, int payloadEndIndex, + private void readDataFrame(ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { int padding = readPadding(payload); verifyPadding(padding); // Determine how much data there is to read by removing the trailing // padding. - int dataLength = lengthWithoutTrailingPadding(payloadEndIndex - payload.readerIndex(), padding); + int dataLength = lengthWithoutTrailingPadding(payload.readableBytes(), padding); - ByteBuf data = payload.readSlice(dataLength); - listener.onDataRead(ctx, streamId, data, padding, flags.endOfStream()); + payload.writerIndex(payload.readerIndex() + dataLength); + listener.onDataRead(ctx, streamId, payload, padding, flags.endOfStream()); } - private void readHeadersFrame(final ChannelHandlerContext ctx, ByteBuf payload, int payloadEndIndex, + private void readHeadersFrame(final ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { final int headersStreamId = streamId; final Http2Flags headersFlags = flags; @@ -432,7 +425,7 @@ private void readHeadersFrame(final ChannelHandlerContext ctx, ByteBuf payload, throw streamError(streamId, PROTOCOL_ERROR, "A stream cannot depend on itself."); } final short weight = (short) (payload.readUnsignedByte() + 1); - final int lenToRead = lengthWithoutTrailingPadding(payloadEndIndex - payload.readerIndex(), padding); + final int lenToRead = lengthWithoutTrailingPadding(payload.readableBytes(), padding); // Create a handler that invokes the listener when the header block is complete. headersContinuation = new HeadersContinuation() { @@ -480,7 +473,7 @@ public void processFragment(boolean endOfHeaders, ByteBuf fragment, int len, }; // Process the initial fragment, invoking the listener's callback if end of headers. - int len = lengthWithoutTrailingPadding(payloadEndIndex - payload.readerIndex(), padding); + int len = lengthWithoutTrailingPadding(payload.readableBytes(), padding); headersContinuation.processFragment(flags.endOfHeaders(), payload, len, listener); resetHeadersContinuationIfEnd(flags.endOfHeaders()); } @@ -533,7 +526,7 @@ private void readSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload, } } - private void readPushPromiseFrame(final ChannelHandlerContext ctx, ByteBuf payload, int payloadEndIndex, + private void readPushPromiseFrame(final ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { final int pushPromiseStreamId = streamId; final int padding = readPadding(payload); @@ -559,7 +552,7 @@ public void processFragment(boolean endOfHeaders, ByteBuf fragment, int len, }; // Process the initial fragment, invoking the listener's callback if end of headers. - int len = lengthWithoutTrailingPadding(payloadEndIndex - payload.readerIndex(), padding); + int len = lengthWithoutTrailingPadding(payload.readableBytes(), padding); headersContinuation.processFragment(flags.endOfHeaders(), payload, len, listener); resetHeadersContinuationIfEnd(flags.endOfHeaders()); } @@ -573,12 +566,11 @@ private void readPingFrame(ChannelHandlerContext ctx, long data, } } - private static void readGoAwayFrame(ChannelHandlerContext ctx, ByteBuf payload, int payloadEndIndex, + private void readGoAwayFrame(ChannelHandlerContext ctx, ByteBuf payload, Http2FrameListener listener) throws Http2Exception { int lastStreamId = readUnsignedInt(payload); long errorCode = payload.readUnsignedInt(); - ByteBuf debugData = payload.readSlice(payloadEndIndex - payload.readerIndex()); - listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData); + listener.onGoAwayRead(ctx, lastStreamId, errorCode, payload); } private void readWindowUpdateFrame(ChannelHandlerContext ctx, ByteBuf payload, @@ -591,17 +583,16 @@ private void readWindowUpdateFrame(ChannelHandlerContext ctx, ByteBuf payload, listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement); } - private void readContinuationFrame(ByteBuf payload, int payloadEndIndex, Http2FrameListener listener) + private void readContinuationFrame(ByteBuf payload, Http2FrameListener listener) throws Http2Exception { // Process the initial fragment, invoking the listener's callback if end of headers. headersContinuation.processFragment(flags.endOfHeaders(), payload, - payloadEndIndex - payload.readerIndex(), listener); + payloadLength, listener); resetHeadersContinuationIfEnd(flags.endOfHeaders()); } private void readUnknownFrame(ChannelHandlerContext ctx, ByteBuf payload, - int payloadEndIndex, Http2FrameListener listener) throws Http2Exception { - payload = payload.readSlice(payloadEndIndex - payload.readerIndex()); + Http2FrameListener listener) throws Http2Exception { listener.onUnknownFrame(ctx, frameType, streamId, flags, payload); }
diff --git a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameReaderTest.java b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameReaderTest.java index bfedf0ac619..8ba309cc617 100644 --- a/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameReaderTest.java +++ b/codec-http2/src/test/java/io/netty/handler/codec/http2/DefaultHttp2FrameReaderTest.java @@ -386,6 +386,45 @@ public void execute() throws Throwable { } } + @Test + public void verifyValidRequestAfterMalformedPacketCausesStreamException() throws Http2Exception { + final ByteBuf input = Unpooled.buffer(); + int priorityStreamId = 3, headerStreamId = 5; + try { + // Write a malformed priority header causing a stream exception in reader + writeFrameHeader(input, 4, PRIORITY, new Http2Flags(), priorityStreamId); + // Fill buffer with dummy payload to be properly read by reader + input.writeByte((byte) 0x80); + input.writeByte((byte) 0x00); + input.writeByte((byte) 0x00); + input.writeByte((byte) 0x7f); + assertThrows(Http2Exception.class, new Executable() { + @Override + public void execute() throws Throwable { + try { + frameReader.readFrame(ctx, input, listener); + } catch (Exception e) { + if (e instanceof Http2Exception && Http2Exception.isStreamError((Http2Exception) e)) { + throw e; + } + } + } + }); + // Verify that after stream exception we accept new stream requests + Http2Headers headers = new DefaultHttp2Headers() + .authority("foo") + .method("get") + .path("/") + .scheme("https"); + Http2Flags flags = new Http2Flags().endOfHeaders(true).endOfStream(true); + writeHeaderFrame(input, headerStreamId, headers, flags); + frameReader.readFrame(ctx, input, listener); + verify(listener).onHeadersRead(ctx, 5, headers, 0, true); + } finally { + input.release(); + } + } + private void writeHeaderFrame( ByteBuf output, int streamId, Http2Headers headers, Http2Flags flags) throws Http2Exception {
train
test
"2024-02-08T10:51:32"
"2024-01-17T20:50:10Z"
isaacrivriv
val