From e98f6fd1fde25c30e677513fd1beb7c07b6a89e3 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 29 Aug 2016 22:04:03 +0200
Subject: [PATCH 001/890] Upgrade Netty 4.0.41
---
pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pom.xml b/pom.xml
index b5ab4f4e91..a4fc7760b5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -379,7 +379,7 @@
true1.81.8
- 4.0.40.Final
+ 4.0.41.Final1.7.211.1.76.9.10
From 0a0cdb81f9dd9c197370b89ba7d4af5281f2c73a Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Mon, 29 Aug 2016 22:11:57 +0200
Subject: [PATCH 002/890] Backport: Removed custom split method as it is not
effective anymore.
---
.../io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
index 3222566e06..2eb61a4444 100644
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
+++ b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
@@ -85,7 +85,7 @@ protected void encodeName(String name, ByteBuf buf) throws Exception {
return;
}
- final String[] labels = StringUtil.split(name, '.');
+ final String[] labels = name.split("\\.");
for (String label : labels) {
final int labelLen = label.length();
if (labelLen == 0) {
From 8f2b8a546dc8c9bbbe23102075c77525d2d76fa1 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 7 Sep 2016 10:12:04 +0200
Subject: [PATCH 003/890] Those are ints
---
.../org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java | 2 +-
.../asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java b/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
index 7f3aae98af..0bd249049c 100755
--- a/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
+++ b/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
@@ -27,7 +27,7 @@ public ReadTimeoutTimerTask(//
NettyResponseFuture> nettyResponseFuture,//
NettyRequestSender requestSender,//
TimeoutsHolder timeoutsHolder,//
- long readTimeout) {
+ int readTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.readTimeout = readTimeout;
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java b/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
index 2546b69142..d108deea44 100755
--- a/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
+++ b/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
@@ -27,7 +27,7 @@ public RequestTimeoutTimerTask(//
NettyResponseFuture> nettyResponseFuture,//
NettyRequestSender requestSender,//
TimeoutsHolder timeoutsHolder,//
- long requestTimeout) {
+ int requestTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.requestTimeout = requestTimeout;
}
From 596d4d941111797dc5dce29200958a5050537c3e Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Wed, 7 Sep 2016 10:12:14 +0200
Subject: [PATCH 004/890] Make constants public
---
.../main/java/org/asynchttpclient/netty/util/Utf8Decoder.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
index db6aeabefa..c4290804ea 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
@@ -36,8 +36,8 @@ public abstract class Utf8Decoder {
12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
};
- protected static final int UTF8_ACCEPT = 0;
- protected static final int UTF8_REJECT = 12;
+ public static final int UTF8_ACCEPT = 0;
+ public static final int UTF8_REJECT = 12;
protected StringBuilder sb = new StringBuilder();
protected int state = UTF8_ACCEPT;
From cbb2cc924fd365c5f6dabf149e86161edbb8da97 Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Fri, 9 Sep 2016 22:40:38 +0200
Subject: [PATCH 005/890] Upgrade netty-reactive-streams 1.0.7
---
client/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/pom.xml b/client/pom.xml
index fffce6e875..51159c36a3 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -52,7 +52,7 @@
com.typesafe.nettynetty-reactive-streams
- 1.0.6
+ 1.0.7org.javassist
From 622c498b468ae9620bc43e1d0befd375573c54ab Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:27:34 +0200
Subject: [PATCH 006/890] Optimize UTF-8 HeapByteBuf(s) to String, close #1245
---
.../netty/ws/NettyWebSocket.java | 3 +-
.../netty/util/ByteBufUtils.java | 39 ++--
.../netty/util/UsAsciiByteBufDecoder.java | 48 ----
.../netty/util/Utf8ByteBufCharsetDecoder.java | 216 ++++++++++++++++++
.../netty/util/Utf8ByteBufDecoder.java | 50 ----
.../netty/util/Utf8Decoder.java | 82 -------
.../netty/util/ByteBufUtilsTest.java | 24 +-
7 files changed, 261 insertions(+), 201 deletions(-)
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
create mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
delete mode 100644 netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
diff --git a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
index b292e45868..c2903056a1 100755
--- a/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
+++ b/client/src/main/java/org/asynchttpclient/netty/ws/NettyWebSocket.java
@@ -14,6 +14,7 @@
package org.asynchttpclient.netty.ws;
import static io.netty.buffer.Unpooled.wrappedBuffer;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.asynchttpclient.netty.util.ByteBufUtils.byteBuf2Bytes;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
@@ -220,7 +221,7 @@ public void onBinaryFrame(BinaryWebSocketFrame frame) {
public void onTextFrame(TextWebSocketFrame frame) {
if (interestedInTextMessages) {
try {
- notifyTextListeners(ByteBufUtils.byteBuf2Utf8String(frame.content()));
+ notifyTextListeners(ByteBufUtils.byteBuf2String(UTF_8, frame.content()));
} catch (CharacterCodingException e) {
throw new IllegalStateException(e);
}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
index 2bf7a65e2c..c5f66ac674 100755
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/ByteBufUtils.java
@@ -13,35 +13,44 @@
*/
package org.asynchttpclient.netty.util;
+import static java.nio.charset.StandardCharsets.*;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.CompositeByteBuf;
+import io.netty.buffer.Unpooled;
-import java.io.UTFDataFormatException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.Collections;
public final class ByteBufUtils {
private ByteBufUtils() {
}
- public static String byteBuf2Utf8String(ByteBuf buf) throws CharacterCodingException {
- return Utf8ByteBufDecoder.pooled().decode(Collections.singleton(buf));
+ public static String byteBuf2String(Charset charset, ByteBuf buf) throws CharacterCodingException {
+ if (charset == UTF_8 || charset == US_ASCII) {
+ return Utf8ByteBufCharsetDecoder.decodeUtf8(buf);
+ } else {
+ return buf.toString(charset);
+ }
}
- public static String byteBuf2UsAsciiString(ByteBuf buf) throws CharacterCodingException {
- return UsAsciiByteBufDecoder.pooled().decode(Collections.singleton(buf));
- }
+ public static String byteBuf2String(Charset charset, ByteBuf... bufs) throws CharacterCodingException {
+ if (charset == UTF_8 || charset == US_ASCII) {
+ return Utf8ByteBufCharsetDecoder.decodeUtf8(bufs);
+ } else {
+ CompositeByteBuf composite = Unpooled.compositeBuffer(bufs.length);
- public static String byteBuf2String(ByteBuf buf, Charset charset) throws UTFDataFormatException, IndexOutOfBoundsException, CharacterCodingException {
+ try {
+ for (ByteBuf buf : bufs) {
+ buf.retain();
+ composite.addComponent(buf);
+ }
- if (charset.equals(StandardCharsets.US_ASCII)) {
- return byteBuf2UsAsciiString(buf);
- } else if (charset.equals(StandardCharsets.UTF_8)) {
- return byteBuf2Utf8String(buf);
- } else {
- return buf.toString(charset);
+ return composite.toString(charset);
+
+ } finally {
+ composite.release();
+ }
}
}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
deleted file mode 100644
index 0dbd9faf38..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/UsAsciiByteBufDecoder.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.concurrent.FastThreadLocal;
-
-public class UsAsciiByteBufDecoder {
-
- private static final FastThreadLocal POOL = new FastThreadLocal() {
- protected UsAsciiByteBufDecoder initialValue() {
- return new UsAsciiByteBufDecoder();
- };
- };
-
- public static UsAsciiByteBufDecoder pooled() {
- UsAsciiByteBufDecoder decoder = POOL.get();
- decoder.reset();
- return decoder;
- }
-
- private StringBuilder sb = new StringBuilder();
-
- public void reset() {
- sb.setLength(0);
- }
-
- public String decode(Iterable bufs) {
- for (ByteBuf buf : bufs) {
- buf.forEachByte(b -> {
- sb.append((char) b);
- return true;
- });
- }
- return sb.toString();
- }
-}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
new file mode 100644
index 0000000000..1274409d7c
--- /dev/null
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
+package org.asynchttpclient.netty.util;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+
+public class Utf8ByteBufCharsetDecoder {
+
+ private static final ThreadLocal POOL = new ThreadLocal() {
+ protected Utf8ByteBufCharsetDecoder initialValue() {
+ return new Utf8ByteBufCharsetDecoder();
+ }
+ };
+
+ private static Utf8ByteBufCharsetDecoder pooledDecoder() {
+ Utf8ByteBufCharsetDecoder decoder = POOL.get();
+ decoder.reset();
+ return decoder;
+ }
+
+ public static String decodeUtf8(ByteBuf buf) throws CharacterCodingException {
+ return pooledDecoder().decode(buf);
+ }
+
+ public static String decodeUtf8(ByteBuf... bufs) throws CharacterCodingException {
+ return pooledDecoder().decode(bufs);
+ }
+
+ private final CharsetDecoder decoder = UTF_8.newDecoder();
+ protected CharBuffer charBuffer = allocateCharBuffer(1024);
+ private ByteBuffer splitCharBuffer;
+
+ protected void initSplitCharBuffer() {
+ if (splitCharBuffer == null) {
+ // UTF-8 chars are 4 bytes max
+ splitCharBuffer = ByteBuffer.allocate(4);
+ }
+ }
+
+ protected CharBuffer allocateCharBuffer(int l) {
+ return CharBuffer.allocate(l);
+ }
+
+ private void ensureCapacity(int l) {
+ if (charBuffer.position() == 0) {
+ if (charBuffer.capacity() < l) {
+ charBuffer = allocateCharBuffer(l);
+ }
+ } else if (charBuffer.remaining() < l) {
+ CharBuffer newCharBuffer = allocateCharBuffer(charBuffer.position() + l);
+ charBuffer.flip();
+ newCharBuffer.put(charBuffer);
+ charBuffer = newCharBuffer;
+ }
+ }
+
+ public void reset() {
+ decoder.reset();
+ charBuffer.position(0);
+ }
+
+ private static int charSize(byte firstByte) throws CharacterCodingException {
+ if ((firstByte >> 5) == -2 && (firstByte & 0x1e) != 0) {
+ // 2 bytes, 11 bits: 110xxxxx 10xxxxxx
+ return 2;
+
+ } else if ((firstByte >> 4) == -2) {
+ // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx
+ return 3;
+
+ } else if ((firstByte >> 3) == -2) {
+ // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ return 4;
+
+ } else {
+ // charSize isn't supposed to be called for regular bytes
+ throw new CharacterCodingException();
+ }
+ }
+
+ private void handleSplitCharBuffer(ByteBuffer nioBuffer, boolean endOfInput) throws CharacterCodingException {
+ // TODO we could save charSize
+ int missingBytes = charSize(splitCharBuffer.get(0)) - splitCharBuffer.position();
+
+ if (nioBuffer.remaining() < missingBytes) {
+ if (endOfInput) {
+ throw new CharacterCodingException();
+ }
+
+ // still not enough bytes
+ splitCharBuffer.put(nioBuffer);
+
+ } else {
+ // FIXME better way?
+ for (int i = 0; i < missingBytes; i++) {
+ splitCharBuffer.put(nioBuffer.get());
+ }
+
+ splitCharBuffer.flip();
+ CoderResult res = decoder.decode(splitCharBuffer, charBuffer, endOfInput && !nioBuffer.hasRemaining());
+ if (res.isError()) {
+ res.throwException();
+ }
+
+ splitCharBuffer.position(0);
+ }
+ }
+
+ protected void decodePartial(ByteBuffer nioBuffer, boolean endOfInput) throws CharacterCodingException {
+ // deal with pending splitCharBuffer
+ if (splitCharBuffer != null && splitCharBuffer.position() > 0 && nioBuffer.hasRemaining()) {
+ handleSplitCharBuffer(nioBuffer, endOfInput);
+ }
+
+ // decode remaining buffer
+ if (nioBuffer.hasRemaining()) {
+ CoderResult res = decoder.decode(nioBuffer, charBuffer, endOfInput);
+ if (res.isUnderflow()) {
+ if (nioBuffer.remaining() > 0) {
+ initSplitCharBuffer();
+ splitCharBuffer.put(nioBuffer);
+ }
+ } else if (res.isError()) {
+ res.throwException();
+ }
+ }
+ }
+
+ private void decode(ByteBuffer[] nioBuffers, int length) throws CharacterCodingException {
+ int count = nioBuffers.length;
+ for (int i = 0; i < count; i++) {
+ decodePartial(nioBuffers[i].duplicate(), i == count - 1);
+ }
+ }
+
+ private void decodeSingleNioBuffer(ByteBuffer nioBuffer, int length) throws CharacterCodingException {
+ CoderResult res = decoder.decode(nioBuffer, charBuffer, true);
+ if (res.isError()) {
+ res.throwException();
+ }
+ }
+
+ public String decode(ByteBuf buf) throws CharacterCodingException {
+ if (buf.isDirect()) {
+ return buf.toString(UTF_8);
+ }
+
+ int length = buf.readableBytes();
+ ensureCapacity(length);
+
+ if (buf.nioBufferCount() == 1) {
+ decodeSingleNioBuffer(buf.internalNioBuffer(buf.readerIndex(), length).duplicate(), length);
+ } else {
+ decode(buf.nioBuffers(), buf.readableBytes());
+ }
+
+ return charBuffer.flip().toString();
+ }
+
+ public String decode(ByteBuf... bufs) throws CharacterCodingException {
+
+ int totalSize = 0;
+ int totalNioBuffers = 0;
+ boolean direct = false;
+ for (ByteBuf buf : bufs) {
+ if (buf.isDirect()) {
+ direct = true;
+ break;
+ }
+ totalSize += buf.readableBytes();
+ totalNioBuffers += buf.nioBufferCount();
+ }
+
+ if (direct) {
+ ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
+ try {
+ return wrappedBuffer.toString(UTF_8);
+ } finally {
+ wrappedBuffer.release();
+ }
+
+ } else {
+ ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
+ int i = 0;
+ for (ByteBuf buf : bufs) {
+ for (ByteBuffer nioBuffer : buf.nioBuffers()) {
+ nioBuffers[i++] = nioBuffer;
+ }
+ }
+
+ ensureCapacity(totalSize);
+ decode(nioBuffers, totalSize);
+
+ return charBuffer.flip().toString();
+ }
+ }
+}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
deleted file mode 100644
index fddcdcdd4c..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufDecoder.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.concurrent.FastThreadLocal;
-
-import java.nio.charset.CharacterCodingException;
-
-public class Utf8ByteBufDecoder extends Utf8Decoder {
-
- private static final FastThreadLocal POOL = new FastThreadLocal() {
- protected Utf8ByteBufDecoder initialValue() {
- return new Utf8ByteBufDecoder();
- };
- };
-
- public static Utf8ByteBufDecoder pooled() {
- Utf8ByteBufDecoder decoder = POOL.get();
- decoder.reset();
- return decoder;
- }
-
- public String decode(Iterable bufs) throws CharacterCodingException {
-
- for (ByteBuf buf : bufs) {
- buf.forEachByte(value -> {
- write(value);
- return true;
- });
- }
-
- if (state == UTF8_ACCEPT) {
- return sb.toString();
- } else {
- throw new CharacterCodingException();
- }
- }
-}
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
deleted file mode 100644
index c4290804ea..0000000000
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8Decoder.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
- *
- * This program is licensed to you under the Apache License Version 2.0,
- * and you may not use this file except in compliance with the Apache License Version 2.0.
- * You may obtain a copy of the Apache License Version 2.0 at
- * http://www.apache.org/licenses/LICENSE-2.0.
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the Apache License Version 2.0 is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
- */
-package org.asynchttpclient.netty.util;
-
-import java.nio.charset.CharacterCodingException;
-
-public abstract class Utf8Decoder {
-
- private static final byte[] TYPES = new byte[] {//
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/**/
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,/**/
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,/**/
- 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,/**/
- 10, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /**/
- };
-
- private static final byte[] STATES = new byte[] {//
- 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,/**/
- 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12,/**/
- 12, 12, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12,/**/
- 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 //
- };
-
- public static final int UTF8_ACCEPT = 0;
- public static final int UTF8_REJECT = 12;
-
- protected StringBuilder sb = new StringBuilder();
- protected int state = UTF8_ACCEPT;
- private int codePoint = 0;
-
- protected void write(byte b) throws CharacterCodingException {
- int t = TYPES[b & 0xFF];
-
- codePoint = state != UTF8_ACCEPT ? (b & 0x3f) | (codePoint << 6) : (0xff >> t) & b;
- state = STATES[state + t];
-
- if (state == UTF8_ACCEPT) {
- if (codePoint < Character.MIN_HIGH_SURROGATE) {
- sb.append((char) codePoint);
- } else {
- appendCodePointChars();
- }
- } else if (state == UTF8_REJECT) {
- throw new CharacterCodingException();
- }
- }
-
- private void appendCodePointChars() {
- if (Character.isBmpCodePoint(codePoint)) {
- sb.append((char) codePoint);
-
- } else if (Character.isValidCodePoint(codePoint)) {
- char charIndexPlus1 = Character.lowSurrogate(codePoint);
- char charIndex = Character.highSurrogate(codePoint);
- sb.append(charIndex).append(charIndexPlus1);
-
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- public void reset() {
- sb.setLength(0);
- state = UTF8_ACCEPT;
- codePoint = 0;
- }
-}
diff --git a/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
index fd80a58f6e..a7da5290f2 100644
--- a/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
+++ b/netty-utils/src/test/java/org/asynchttpclient/netty/util/ByteBufUtilsTest.java
@@ -1,5 +1,19 @@
+/*
+ * Copyright (c) 2016 AsyncHttpClient Project. All rights reserved.
+ *
+ * This program is licensed to you under the Apache License Version 2.0,
+ * and you may not use this file except in compliance with the Apache License Version 2.0.
+ * You may obtain a copy of the Apache License Version 2.0 at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the Apache License Version 2.0 is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
+ */
package org.asynchttpclient.netty.util;
+import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.testng.Assert.assertEquals;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -10,18 +24,18 @@ public class ByteBufUtilsTest {
@Test
public void testByteBuf2BytesHasBackingArray() {
- byte[] input = "testdata".getBytes();
- ByteBuf inputBuf = Unpooled.copiedBuffer(input);
+ byte[] inputBytes = "testdata".getBytes(US_ASCII);
+ ByteBuf inputBuf = Unpooled.wrappedBuffer(inputBytes);
byte[] output = ByteBufUtils.byteBuf2Bytes(inputBuf);
- assertEquals(output, input, "The bytes returned by byteBuf2Bytes do not match the bytes in the ByteBuf parameter");
+ assertEquals(output, inputBytes);
}
@Test
public void testByteBuf2BytesNoBackingArray() {
+ byte[] inputBytes = "testdata".getBytes(US_ASCII);
ByteBuf inputBuf = Unpooled.directBuffer();
- byte[] inputBytes = "testdata".getBytes();
inputBuf.writeBytes(inputBytes);
byte[] output = ByteBufUtils.byteBuf2Bytes(inputBuf);
- assertEquals(output, inputBytes, "The bytes returned by byteBuf2Bytes do not match the bytes in the ByteBuf parameter");
+ assertEquals(output, inputBytes);
}
}
From 5d027b10f5e5f7d1279af8f61ef415c0938f3d2f Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:33:03 +0200
Subject: [PATCH 007/890] [maven-release-plugin] prepare release
async-http-client-project-2.0.15
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 51159c36a3..7b8c67d3fa 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index a71a8362b4..217f12c9c7 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index 8de1fcfcad..d11049e921 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 417e554bb4..9a1eb9d7dd 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 5f4bbb2dd5..de7a2b8bcf 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index c39037e117..7677e6cf3d 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index 05d4f93c3c..bd311d3239 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15-SNAPSHOT
+ 2.0.15async-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index c7a21ff88a..63cf0f16d8 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index bbe5182a05..175f38af13 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index 749bf0c075..c6c0d596af 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index c9039801b7..0fdb75246c 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15-SNAPSHOT
+ 2.0.15netty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index a70646b204..6db7dea0de 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15-SNAPSHOT
+ 2.0.154.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index a4fc7760b5..86b0641f64 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.15-SNAPSHOT
+ 2.0.15pom
The Async Http Client (AHC) library's purpose is to allow Java
From 676a28bf82c5a90fcff63f079cebd9628b2513af Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sat, 10 Sep 2016 23:33:10 +0200
Subject: [PATCH 008/890] [maven-release-plugin] prepare for next development
iteration
---
client/pom.xml | 2 +-
extras/guava/pom.xml | 2 +-
extras/jdeferred/pom.xml | 2 +-
extras/pom.xml | 2 +-
extras/registry/pom.xml | 2 +-
extras/rxjava/pom.xml | 2 +-
extras/simple/pom.xml | 2 +-
netty-bp/codec-dns/pom.xml | 2 +-
netty-bp/pom.xml | 2 +-
netty-bp/resolver-dns/pom.xml | 2 +-
netty-bp/resolver/pom.xml | 2 +-
netty-utils/pom.xml | 2 +-
pom.xml | 2 +-
13 files changed, 13 insertions(+), 13 deletions(-)
diff --git a/client/pom.xml b/client/pom.xml
index 7b8c67d3fa..1b0f7bd327 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 217f12c9c7..aec5d9435e 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index d11049e921..dda4498657 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index 9a1eb9d7dd..811f531089 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index de7a2b8bcf..e1906e8a5b 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 7677e6cf3d..a3fda543c1 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index bd311d3239..bc402747b5 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.15
+ 2.0.16-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
index 63cf0f16d8..18f123e93c 100644
--- a/netty-bp/codec-dns/pom.xml
+++ b/netty-bp/codec-dns/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-codec-dns
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
index 175f38af13..8d40fd4704 100644
--- a/netty-bp/pom.xml
+++ b/netty-bp/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0netty-bp
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
index c6c0d596af..f7e8499c9d 100644
--- a/netty-bp/resolver-dns/pom.xml
+++ b/netty-bp/resolver-dns/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-resolver-dns
diff --git a/netty-bp/resolver/pom.xml b/netty-bp/resolver/pom.xml
index 0fdb75246c..55de914163 100644
--- a/netty-bp/resolver/pom.xml
+++ b/netty-bp/resolver/pom.xml
@@ -20,7 +20,7 @@
org.asynchttpclientnetty-bp
- 2.0.15
+ 2.0.16-SNAPSHOTnetty-resolver
diff --git a/netty-utils/pom.xml b/netty-utils/pom.xml
index 6db7dea0de..bf6b58e705 100644
--- a/netty-utils/pom.xml
+++ b/netty-utils/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.15
+ 2.0.16-SNAPSHOT4.0.0async-http-client-netty-utils
diff --git a/pom.xml b/pom.xml
index 86b0641f64..eb1463fee2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,7 +9,7 @@
org.asynchttpclientasync-http-client-projectAsynchronous Http Client Project
- 2.0.15
+ 2.0.16-SNAPSHOTpom
The Async Http Client (AHC) library's purpose is to allow Java
From ba16cfc938d90f8d7fa3e6b7f484fc7baf9daebc Mon Sep 17 00:00:00 2001
From: Stephane Landelle
Date: Sun, 11 Sep 2016 00:01:56 +0200
Subject: [PATCH 009/890] Short path when one single buf
---
.../asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
index 1274409d7c..ccc35c27dd 100644
--- a/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
+++ b/netty-utils/src/main/java/org/asynchttpclient/netty/util/Utf8ByteBufCharsetDecoder.java
@@ -177,6 +177,9 @@ public String decode(ByteBuf buf) throws CharacterCodingException {
}
public String decode(ByteBuf... bufs) throws CharacterCodingException {
+ if (bufs.length == 1) {
+ return decode(bufs[0]);
+ }
int totalSize = 0;
int totalNioBuffers = 0;
From d72b89e042b41b8f32d4883702a37886d00e23ac Mon Sep 17 00:00:00 2001
From: Dmitriy Dumanskiy
Date: Mon, 12 Sep 2016 23:34:03 +0300
Subject: [PATCH 010/890] #1246 added "ThreadSafe" in comments section for
DefaultAsyncHttpClient
---
.../main/java/org/asynchttpclient/DefaultAsyncHttpClient.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
index 897b6e25e8..db884e55ad 100644
--- a/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
+++ b/client/src/main/java/org/asynchttpclient/DefaultAsyncHttpClient.java
@@ -33,6 +33,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+/**
+ * Default and threadsafe implementation of {@link AsyncHttpClient}.
+ */
public class DefaultAsyncHttpClient implements AsyncHttpClient {
private final static Logger LOGGER = LoggerFactory.getLogger(DefaultAsyncHttpClient.class);
From 8fb7c9d236251d8df4671a74ca48ab198e34d5a5 Mon Sep 17 00:00:00 2001
From: Tom Wieczorek
Date: Sun, 18 Sep 2016 18:05:14 +0200
Subject: [PATCH 011/890] Enable asynchronous cancellation of AsyncHttpSingle.
(#1250)
AsyncHttpSingle is currently not forwarding an unsubscription to AsyncHttpClient, it just aborts request processing when an AsyncHandler callback method is invoked. To actually eagerly cancel a request on unsubscription, use the request future to actually forward the cancellation to AsyncHttpClient.
---
.../extras/rxjava/UnsubscribedException.java | 6 ++--
.../extras/rxjava/single/AsyncHttpSingle.java | 25 +++++++++++----
.../rxjava/single/AsyncHttpSingleTest.java | 32 +++++++++++++++++++
3 files changed, 55 insertions(+), 8 deletions(-)
diff --git a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
index f954f7236e..c1a7099dbe 100644
--- a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
+++ b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/UnsubscribedException.java
@@ -12,16 +12,18 @@
*/
package org.asynchttpclient.extras.rxjava;
+import java.util.concurrent.CancellationException;
+
/**
* Indicates that an {@code Observer} unsubscribed during the processing of a HTTP request.
*/
@SuppressWarnings("serial")
-public class UnsubscribedException extends RuntimeException {
+public class UnsubscribedException extends CancellationException {
public UnsubscribedException() {
}
public UnsubscribedException(final Throwable cause) {
- super(cause);
+ initCause(cause);
}
}
diff --git a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
index d244fbba84..4e95aab846 100644
--- a/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
+++ b/extras/rxjava/src/main/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingle.java
@@ -20,10 +20,13 @@
import org.asynchttpclient.Response;
import org.asynchttpclient.handler.ProgressAsyncHandler;
+import java.util.concurrent.Future;
+
import rx.Single;
import rx.SingleSubscriber;
-import rx.functions.Action1;
import rx.functions.Func0;
+import rx.functions.Func1;
+import rx.subscriptions.Subscriptions;
/**
* Wraps HTTP requests into RxJava {@code Single} instances.
@@ -54,14 +57,17 @@ public static Single create(BoundRequestBuilder builder) {
*
* @param requestTemplate called to start the HTTP request with an
* {@code AysncHandler} that builds the HTTP response and
- * propagates results to the returned {@code Single}
+ * propagates results to the returned {@code Single}. The
+ * {@code Future} that is returned by {@code requestTemplate}
+ * will be used to cancel the request when the {@code Single} is
+ * unsubscribed.
*
* @return a {@code Single} that executes new requests on subscription by
* calling {@code requestTemplate} and that emits the response
*
* @throws NullPointerException if {@code requestTemplate} is {@code null}
*/
- public static Single create(Action1 super AsyncHandler>> requestTemplate) {
+ public static Single create(Func1 super AsyncHandler>, ? extends Future>> requestTemplate) {
return create(requestTemplate, AsyncCompletionHandlerBase::new);
}
@@ -92,7 +98,10 @@ public static Single create(BoundRequestBuilder builder, Func0 extends
*
* @param requestTemplate called to start the HTTP request with an
* {@code AysncHandler} that builds the HTTP response and
- * propagates results to the returned {@code Single}
+ * propagates results to the returned {@code Single}. The
+ * {@code Future} that is returned by {@code requestTemplate}
+ * will be used to cancel the request when the {@code Single} is
+ * unsubscribed.
* @param handlerSupplier supplies the desired {@code AsyncHandler}
* instances that are used to produce results
*
@@ -104,13 +113,17 @@ public static Single create(BoundRequestBuilder builder, Func0 extends
* @throws NullPointerException if at least one of the parameters is
* {@code null}
*/
- public static Single create(Action1 super AsyncHandler>> requestTemplate,
+ public static Single create(Func1 super AsyncHandler>, ? extends Future>> requestTemplate,
Func0 extends AsyncHandler extends T>> handlerSupplier) {
requireNonNull(requestTemplate);
requireNonNull(handlerSupplier);
- return Single.create(subscriber -> requestTemplate.call(createBridge(subscriber, handlerSupplier.call())));
+ return Single.create(subscriber -> {
+ final AsyncHandler> bridge = createBridge(subscriber, handlerSupplier.call());
+ final Future> responseFuture = requestTemplate.call(bridge);
+ subscriber.add(Subscriptions.from(responseFuture));
+ });
}
static AsyncHandler> createBridge(SingleSubscriber super T> subscriber, AsyncHandler extends T> handler) {
diff --git a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
index d0039bc73f..83ada0a068 100644
--- a/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
+++ b/extras/rxjava/src/test/java/org/asynchttpclient/extras/rxjava/single/AsyncHttpSingleTest.java
@@ -18,6 +18,7 @@
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -25,6 +26,7 @@
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
@@ -34,13 +36,16 @@
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.Response;
+import org.asynchttpclient.extras.rxjava.UnsubscribedException;
import org.asynchttpclient.handler.ProgressAsyncHandler;
import org.mockito.InOrder;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
+import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import rx.Single;
import rx.exceptions.CompositeException;
@@ -82,6 +87,8 @@ public void testSuccessfulCompletion() throws Exception {
} catch (final Throwable t) {
bridge.onThrowable(t);
}
+
+ return mock(Future.class);
} , () -> handler);
final TestSubscriber
- org.asynchttpclient
+ io.nettynetty-resolver-dns
- ${project.version}org.reactivestreams
diff --git a/client/src/main/java/io/netty/channel/ChannelId.java b/client/src/main/java/io/netty/channel/ChannelId.java
deleted file mode 100644
index 5baa48f2a3..0000000000
--- a/client/src/main/java/io/netty/channel/ChannelId.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.channel;
-
-import java.io.Serializable;
-
-/**
- * Represents the globally unique identifier of a {@link Channel}.
- *
- * The identifier is generated from various sources listed in the following:
- *
- *
MAC address (EUI-48 or EUI-64) or the network adapter, preferably a globally unique one,
- *
the current process ID,
- *
{@link System#currentTimeMillis()},
- *
{@link System#nanoTime()},
- *
a random 32-bit integer, and
- *
a sequentially incremented 32-bit integer.
- *
- *
- * The global uniqueness of the generated identifier mostly depends on the MAC address and the current process ID,
- * which are auto-detected at the class-loading time in best-effort manner. If all attempts to acquire them fail,
- * a warning message is logged, and random values will be used instead. Alternatively, you can specify them manually
- * via system properties:
- *
- *
{@code io.netty.machineId} - hexadecimal representation of 48 (or 64) bit integer,
- * optionally separated by colon or hyphen.
- *
{@code io.netty.processId} - an integer between 0 and 65535
- *
- */
-public interface ChannelId extends Serializable, Comparable {
- /**
- * @return the short but globally non-unique string representation of the {@link ChannelId}.
- */
- String asShortText();
-
- /**
- * @return the long yet globally unique string representation of the {@link ChannelId}.
- */
- String asLongText();
-}
diff --git a/client/src/main/java/io/netty/channel/DefaultChannelId.java b/client/src/main/java/io/netty/channel/DefaultChannelId.java
deleted file mode 100644
index 3e7c42c3b3..0000000000
--- a/client/src/main/java/io/netty/channel/DefaultChannelId.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.channel;
-
-import io.netty.buffer.ByteBufUtil;
-import io.netty.util.internal.MacAddressUtil;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.PlatformDependent;
-import io.netty.util.internal.SystemPropertyUtil;
-import io.netty.util.internal.ThreadLocalRandom;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Pattern;
-
-/**
- * The default {@link ChannelId} implementation.
- */
-public final class DefaultChannelId implements ChannelId {
-
- private static final long serialVersionUID = 3884076183504074063L;
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelId.class);
-
- private static final Pattern MACHINE_ID_PATTERN = Pattern.compile("^(?:[0-9a-fA-F][:-]?){6,8}$");
- private static final int MACHINE_ID_LEN = MacAddressUtil.MAC_ADDRESS_LENGTH;
- private static final byte[] MACHINE_ID;
- private static final int PROCESS_ID_LEN = 4;
- // Maximal value for 64bit systems is 2^22. See man 5 proc.
- // See https://github.com/netty/netty/issues/2706
- private static final int MAX_PROCESS_ID = 4194304;
- private static final int PROCESS_ID;
- private static final int SEQUENCE_LEN = 4;
- private static final int TIMESTAMP_LEN = 8;
- private static final int RANDOM_LEN = 4;
-
- private static final AtomicInteger nextSequence = new AtomicInteger();
-
- static ChannelId newInstance() {
- DefaultChannelId id = new DefaultChannelId();
- id.init();
- return id;
- }
-
- static {
- int processId = -1;
- String customProcessId = SystemPropertyUtil.get("io.netty.processId");
- if (customProcessId != null) {
- try {
- processId = Integer.parseInt(customProcessId);
- } catch (NumberFormatException e) {
- // Malformed input.
- }
-
- if (processId < 0 || processId > MAX_PROCESS_ID) {
- processId = -1;
- logger.warn("-Dio.netty.processId: {} (malformed)", customProcessId);
- } else if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.processId: {} (user-set)", processId);
- }
- }
-
- if (processId < 0) {
- processId = defaultProcessId();
- if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.processId: {} (auto-detected)", processId);
- }
- }
-
- PROCESS_ID = processId;
-
- byte[] machineId = null;
- String customMachineId = SystemPropertyUtil.get("io.netty.machineId");
- if (customMachineId != null) {
- if (MACHINE_ID_PATTERN.matcher(customMachineId).matches()) {
- machineId = parseMachineId(customMachineId);
- logger.debug("-Dio.netty.machineId: {} (user-set)", customMachineId);
- } else {
- logger.warn("-Dio.netty.machineId: {} (malformed)", customMachineId);
- }
- }
-
- if (machineId == null) {
- machineId = defaultMachineId();
- if (logger.isDebugEnabled()) {
- logger.debug("-Dio.netty.machineId: {} (auto-detected)", MacAddressUtil.formatAddress(machineId));
- }
- }
-
- MACHINE_ID = machineId;
- }
-
- @SuppressWarnings("DynamicRegexReplaceableByCompiledPattern")
- private static byte[] parseMachineId(String value) {
- // Strip separators.
- value = value.replaceAll("[:-]", "");
-
- byte[] machineId = new byte[MACHINE_ID_LEN];
- for (int i = 0; i < value.length(); i += 2) {
- machineId[i] = (byte) Integer.parseInt(value.substring(i, i + 2), 16);
- }
-
- return machineId;
- }
-
- private static byte[] defaultMachineId() {
- byte[] bestMacAddr = MacAddressUtil.bestAvailableMac();
- if (bestMacAddr == null) {
- bestMacAddr = new byte[MacAddressUtil.MAC_ADDRESS_LENGTH];
- ThreadLocalRandom.current().nextBytes(bestMacAddr);
- logger.warn(
- "Failed to find a usable hardware address from the network interfaces; using random bytes: {}",
- MacAddressUtil.formatAddress(bestMacAddr));
- }
- return bestMacAddr;
- }
-
- private static int defaultProcessId() {
- final ClassLoader loader = PlatformDependent.getSystemClassLoader();
- String value;
- try {
- // Invoke java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
- Class> mgmtFactoryType = Class.forName("java.lang.management.ManagementFactory", true, loader);
- Class> runtimeMxBeanType = Class.forName("java.lang.management.RuntimeMXBean", true, loader);
-
- Method getRuntimeMXBean = mgmtFactoryType.getMethod("getRuntimeMXBean", EmptyArrays.EMPTY_CLASSES);
- Object bean = getRuntimeMXBean.invoke(null, EmptyArrays.EMPTY_OBJECTS);
- Method getName = runtimeMxBeanType.getDeclaredMethod("getName", EmptyArrays.EMPTY_CLASSES);
- value = (String) getName.invoke(bean, EmptyArrays.EMPTY_OBJECTS);
- } catch (Exception e) {
- logger.debug("Could not invoke ManagementFactory.getRuntimeMXBean().getName(); Android?", e);
- try {
- // Invoke android.os.Process.myPid()
- Class> processType = Class.forName("android.os.Process", true, loader);
- Method myPid = processType.getMethod("myPid", EmptyArrays.EMPTY_CLASSES);
- value = myPid.invoke(null, EmptyArrays.EMPTY_OBJECTS).toString();
- } catch (Exception e2) {
- logger.debug("Could not invoke Process.myPid(); not Android?", e2);
- value = "";
- }
- }
-
- int atIndex = value.indexOf('@');
- if (atIndex >= 0) {
- value = value.substring(0, atIndex);
- }
-
- int pid;
- try {
- pid = Integer.parseInt(value);
- } catch (NumberFormatException e) {
- // value did not contain an integer.
- pid = -1;
- }
-
- if (pid < 0 || pid > MAX_PROCESS_ID) {
- pid = ThreadLocalRandom.current().nextInt(MAX_PROCESS_ID + 1);
- logger.warn("Failed to find the current process ID from '{}'; using a random value: {}", value, pid);
- }
-
- return pid;
- }
-
- private final byte[] data = new byte[MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN];
- private int hashCode;
-
- private transient String shortValue;
- private transient String longValue;
-
- private void init() {
- int i = 0;
-
- // machineId
- System.arraycopy(MACHINE_ID, 0, data, i, MACHINE_ID_LEN);
- i += MACHINE_ID_LEN;
-
- // processId
- i = writeInt(i, PROCESS_ID);
-
- // sequence
- i = writeInt(i, nextSequence.getAndIncrement());
-
- // timestamp (kind of)
- i = writeLong(i, Long.reverse(System.nanoTime()) ^ System.currentTimeMillis());
-
- // random
- int random = ThreadLocalRandom.current().nextInt();
- hashCode = random;
- i = writeInt(i, random);
-
- assert i == data.length;
- }
-
- private int writeInt(int i, int value) {
- data[i ++] = (byte) (value >>> 24);
- data[i ++] = (byte) (value >>> 16);
- data[i ++] = (byte) (value >>> 8);
- data[i ++] = (byte) value;
- return i;
- }
-
- private int writeLong(int i, long value) {
- data[i ++] = (byte) (value >>> 56);
- data[i ++] = (byte) (value >>> 48);
- data[i ++] = (byte) (value >>> 40);
- data[i ++] = (byte) (value >>> 32);
- data[i ++] = (byte) (value >>> 24);
- data[i ++] = (byte) (value >>> 16);
- data[i ++] = (byte) (value >>> 8);
- data[i ++] = (byte) value;
- return i;
- }
-
- @Override
- public String asShortText() {
- String shortValue = this.shortValue;
- if (shortValue == null) {
- this.shortValue = shortValue = ByteBufUtil.hexDump(
- data, MACHINE_ID_LEN + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN, RANDOM_LEN);
- }
- return shortValue;
- }
-
- @Override
- public String asLongText() {
- String longValue = this.longValue;
- if (longValue == null) {
- this.longValue = longValue = newLongValue();
- }
- return longValue;
- }
-
- private String newLongValue() {
- StringBuilder buf = new StringBuilder(2 * data.length + 5);
- int i = 0;
- i = appendHexDumpField(buf, i, MACHINE_ID_LEN);
- i = appendHexDumpField(buf, i, PROCESS_ID_LEN);
- i = appendHexDumpField(buf, i, SEQUENCE_LEN);
- i = appendHexDumpField(buf, i, TIMESTAMP_LEN);
- i = appendHexDumpField(buf, i, RANDOM_LEN);
- assert i == data.length;
- return buf.substring(0, buf.length() - 1);
- }
-
- private int appendHexDumpField(StringBuilder buf, int i, int length) {
- buf.append(ByteBufUtil.hexDump(data, i, length));
- buf.append('-');
- i += length;
- return i;
- }
-
- @Override
- public int hashCode() {
- return hashCode;
- }
-
- @Override
- public int compareTo(ChannelId o) {
- return 0;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
-
- if (!(obj instanceof DefaultChannelId)) {
- return false;
- }
-
- return Arrays.equals(data, ((DefaultChannelId) obj).data);
- }
-
- @Override
- public String toString() {
- return asShortText();
- }
-}
\ No newline at end of file
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
index 2c76a78d96..1e61514af4 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/Channels.java
@@ -13,14 +13,12 @@
*/
package org.asynchttpclient.netty.channel;
-import java.util.concurrent.atomic.AtomicBoolean;
-
import io.netty.channel.Channel;
-import io.netty.channel.ChannelId;
-import io.netty.channel.DefaultChannelId;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
+import java.util.concurrent.atomic.AtomicBoolean;
+
import org.asynchttpclient.netty.DiscardEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,7 +28,6 @@ public class Channels {
private static final Logger LOGGER = LoggerFactory.getLogger(Channels.class);
private static final AttributeKey DEFAULT_ATTRIBUTE = AttributeKey.valueOf("default");
- private static final AttributeKey CHANNEL_ID_ATTRIBUTE = AttributeKey.valueOf("channelId");
private static final AttributeKey INACTIVE_TOKEN_ATTRIBUTE = AttributeKey.valueOf("inactiveToken");
public static Object getAttribute(Channel channel) {
@@ -58,15 +55,6 @@ public static boolean getInactiveToken(Channel channel) {
return channel != null && channel.attr(INACTIVE_TOKEN_ATTRIBUTE).get().getAndSet(false);
}
- public static ChannelId getChannelId(Channel channel) {
- Attribute attr = channel.attr(CHANNEL_ID_ATTRIBUTE);
- return attr != null ? attr.get() : null;
- }
-
- public static void initChannelId(Channel channel) {
- channel.attr(CHANNEL_ID_ATTRIBUTE).set(new DefaultChannelId());
- }
-
public static void silentlyCloseChannel(Channel channel) {
try {
if (channel != null && channel.isActive())
diff --git a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
index 878db3a290..7ff310e02c 100755
--- a/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
+++ b/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
@@ -58,10 +58,6 @@ public DefaultChannelPool(AsyncHttpClientConfig config, Timer hashedWheelTimer)
config.getConnectionPoolCleanerPeriod());
}
- private ChannelId channelId(Channel channel) {
- return Channels.getChannelId(channel);
- }
-
public DefaultChannelPool(int maxIdleTime,//
int connectionTtl,//
Timer nettyTimer,//
@@ -136,7 +132,7 @@ private boolean isTtlExpired(Channel channel, long now) {
if (!connectionTtlEnabled)
return false;
- ChannelCreation creation = channelId2Creation.get(channelId(channel));
+ ChannelCreation creation = channelId2Creation.get(channel.id());
return creation != null && now - creation.creationTime >= connectionTtl;
}
@@ -218,7 +214,7 @@ public void run(Timeout timeout) throws Exception {
if (!closedChannels.isEmpty()) {
if (connectionTtlEnabled) {
for (IdleChannel closedChannel : closedChannels)
- channelId2Creation.remove(channelId(closedChannel.channel));
+ channelId2Creation.remove(closedChannel.channel.id());
}
partition.removeAll(closedChannels);
@@ -264,7 +260,7 @@ private boolean offer0(Channel channel, Object partitionKey, long now) {
}
private void registerChannelCreation(Channel channel, Object partitionKey, long now) {
- ChannelId id = channelId(channel);
+ ChannelId id = channel.id();
if (!channelId2Creation.containsKey(id)) {
channelId2Creation.putIfAbsent(id, new ChannelCreation(now, partitionKey));
}
@@ -300,7 +296,7 @@ else if (isRemotelyClosed(idleChannel.channel)) {
* {@inheritDoc}
*/
public boolean removeAll(Channel channel) {
- ChannelCreation creation = connectionTtlEnabled ? channelId2Creation.remove(channelId(channel)) : null;
+ ChannelCreation creation = connectionTtlEnabled ? channelId2Creation.remove(channel.id()) : null;
return !isClosed.get() && creation != null && partitions.get(creation.partitionKey).remove(channel);
}
@@ -328,7 +324,7 @@ private void close(Channel channel) {
// FIXME pity to have to do this here
Channels.setDiscard(channel);
if (connectionTtlEnabled) {
- channelId2Creation.remove(channelId(channel));
+ channelId2Creation.remove(channel.id());
}
Channels.silentlyCloseChannel(channel);
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java b/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
index 2540eb2fbf..c14453c0ee 100644
--- a/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/NettyChannelConnector.java
@@ -26,7 +26,6 @@
import org.asynchttpclient.AsyncHttpClientState;
import org.asynchttpclient.handler.AsyncHandlerExtensions;
import org.asynchttpclient.netty.SimpleChannelFutureListener;
-import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.channel.NettyConnectListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,7 +38,6 @@ public class NettyChannelConnector {
private final InetSocketAddress localAddress;
private final List remoteAddresses;
private final AsyncHttpClientState clientState;
- private final boolean connectionTtlEnabled;
private volatile int i = 0;
public NettyChannelConnector(InetAddress localAddress,//
@@ -51,7 +49,6 @@ public NettyChannelConnector(InetAddress localAddress,//
this.remoteAddresses = remoteAddresses;
this.asyncHandlerExtensions = toAsyncHandlerExtensions(asyncHandler);
this.clientState = clientState;
- this.connectionTtlEnabled = config.getConnectionTtl() > 0;
}
private boolean pickNextRemoteAddress() {
@@ -86,9 +83,6 @@ public void onSuccess(Channel channel) {
if (asyncHandlerExtensions != null) {
asyncHandlerExtensions.onTcpConnectSuccess(remoteAddress, channel);
}
- if (connectionTtlEnabled) {
- Channels.initChannelId(channel);
- }
connectListener.onSuccess(channel, remoteAddress);
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
index a0d53b048a..b208308fe8 100755
--- a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
@@ -15,6 +15,7 @@
import static org.asynchttpclient.util.Assertions.assertNotNull;
import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.stream.ChunkedInput;
@@ -30,10 +31,12 @@ public class BodyChunkedInput implements ChunkedInput {
private final Body body;
private final int chunkSize;
private boolean endOfInput;
+ private final long contentLength;
+ private long progress = 0L;
public BodyChunkedInput(Body body) {
this.body = assertNotNull(body, "body");
- long contentLength = body.getContentLength();
+ this.contentLength = body.getContentLength();
if (contentLength <= 0)
chunkSize = DEFAULT_CHUNK_SIZE;
else
@@ -41,12 +44,18 @@ public BodyChunkedInput(Body body) {
}
@Override
- public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
+ @Deprecated
+ public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
+ return readChunk(ctx.alloc());
+ }
+
+ @Override
+ public ByteBuf readChunk(ByteBufAllocator alloc) throws Exception {
if (endOfInput)
return null;
- ByteBuf buffer = ctx.alloc().buffer(chunkSize);
+ ByteBuf buffer = alloc.buffer(chunkSize);
Body.BodyState state = body.transferTo(buffer);
switch (state) {
case STOP:
@@ -72,4 +81,14 @@ public boolean isEndOfInput() throws Exception {
public void close() throws Exception {
body.close();
}
+
+ @Override
+ public long length() {
+ return contentLength;
+ }
+
+ @Override
+ public long progress() {
+ return progress;
+ }
}
diff --git a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
index bd419a6f79..59ef476d03 100755
--- a/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
+++ b/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
@@ -24,6 +24,7 @@
import java.io.IOException;
import java.nio.channels.WritableByteChannel;
+
/**
* Adapts a {@link RandomAccessBody} to Netty's {@link FileRegion}.
*/
@@ -48,9 +49,36 @@ public long count() {
@Override
public long transfered() {
+ return transferred();
+ }
+
+ @Override
+ public long transferred() {
return transferred;
}
+ @Override
+ public FileRegion retain() {
+ super.retain();
+ return this;
+ }
+
+ @Override
+ public FileRegion retain(int arg0) {
+ super.retain(arg0);
+ return this;
+ }
+
+ @Override
+ public FileRegion touch() {
+ return this;
+ }
+
+ @Override
+ public FileRegion touch(Object arg0) {
+ return this;
+ }
+
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
long written = body.transferTo(target);
diff --git a/client/src/test/java/org/asynchttpclient/BasicHttpTest.java b/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
index 7d0132b467..9b22a26cc9 100755
--- a/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
+++ b/client/src/test/java/org/asynchttpclient/BasicHttpTest.java
@@ -925,7 +925,7 @@ public void postUnboundedInputStreamAsBodyStream() throws Throwable {
withClient().run(client -> {
withServer(server).run(server -> {
HttpHeaders h = new DefaultHttpHeaders();
- h.add(CONTENT_TYPE, APPLICATION_JSON);
+ h.add(CONTENT_TYPE, "application/json"); //FIXME
server.enqueue(new AbstractHandler() {
EchoHandler chain = new EchoHandler();
@Override
@@ -959,7 +959,7 @@ public void postInputStreamWithContentLengthAsBodyGenerator() throws Throwable {
withClient().run(client -> {
withServer(server).run(server -> {
HttpHeaders h = new DefaultHttpHeaders();
- h.add(CONTENT_TYPE, APPLICATION_JSON);
+ h.add(CONTENT_TYPE, "application/json"); //FIXME
server.enqueue(new AbstractHandler() {
EchoHandler chain = new EchoHandler();
@Override
diff --git a/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
index 760ec24238..edb194b0ff 100644
--- a/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
+++ b/client/src/test/java/org/asynchttpclient/EofTerminatedTest.java
@@ -51,7 +51,8 @@ public AbstractHandler configureHandler() throws Exception {
@Test(enabled = false)
public void testEolTerminatedResponse() throws Exception {
try (AsyncHttpClient ahc = asyncHttpClient(config().setMaxRequestRetry(0))) {
- ahc.executeRequest(ahc.prepareGet(getTargetUrl()).setHeader(ACCEPT_ENCODING, GZIP_DEFLATE).setHeader(CONNECTION, CLOSE).build()).get();
+ //FIXME
+ ahc.executeRequest(ahc.prepareGet(getTargetUrl()).setHeader(ACCEPT_ENCODING, "gzip, deflate").setHeader(CONNECTION, CLOSE).build()).get();
}
}
}
diff --git a/example/pom.xml b/example/pom.xml
index 10fe7285b1..1e1eacaee5 100644
--- a/example/pom.xml
+++ b/example/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-example
diff --git a/extras/guava/pom.xml b/extras/guava/pom.xml
index 922c22e062..76c56ec764 100644
--- a/extras/guava/pom.xml
+++ b/extras/guava/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-guava
diff --git a/extras/jdeferred/pom.xml b/extras/jdeferred/pom.xml
index b48bf7c370..1734d2b3d6 100644
--- a/extras/jdeferred/pom.xml
+++ b/extras/jdeferred/pom.xml
@@ -18,7 +18,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-jdeferredAsynchronous Http Client JDeferred Extras
diff --git a/extras/pom.xml b/extras/pom.xml
index a59811c5fa..332f93c4bb 100644
--- a/extras/pom.xml
+++ b/extras/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-project
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-parent
diff --git a/extras/registry/pom.xml b/extras/registry/pom.xml
index 626243671f..49d0318db4 100644
--- a/extras/registry/pom.xml
+++ b/extras/registry/pom.xml
@@ -2,7 +2,7 @@
org.asynchttpclientasync-http-client-extras-parent
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOT4.0.0async-http-client-extras-registry
diff --git a/extras/rxjava/pom.xml b/extras/rxjava/pom.xml
index 25840422db..2d60b43eb3 100644
--- a/extras/rxjava/pom.xml
+++ b/extras/rxjava/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-rxjavaAsynchronous Http Client RxJava Extras
diff --git a/extras/simple/pom.xml b/extras/simple/pom.xml
index aa01ec4879..5d4306d00e 100644
--- a/extras/simple/pom.xml
+++ b/extras/simple/pom.xml
@@ -3,7 +3,7 @@
async-http-client-extras-parentorg.asynchttpclient
- 2.0.25-SNAPSHOT
+ 2.1.0-SNAPSHOTasync-http-client-extras-simpleAsynchronous Http Simple Client
diff --git a/netty-bp/codec-dns/pom.xml b/netty-bp/codec-dns/pom.xml
deleted file mode 100644
index 568e91b75f..0000000000
--- a/netty-bp/codec-dns/pom.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
- 4.0.0
-
- org.asynchttpclient
- netty-bp
- 2.0.25-SNAPSHOT
-
-
- netty-codec-dns
-
- Netty/Codec/DNS
-
-
-
- io.netty
- netty-codec
-
-
-
-
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
deleted file mode 100644
index 697a33a808..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.util.AbstractReferenceCounted;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.ReferenceCounted;
-import io.netty.util.ResourceLeak;
-import io.netty.util.ResourceLeakDetector;
-import io.netty.util.internal.StringUtil;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A skeletal implementation of {@link DnsMessage}.
- */
-public abstract class AbstractDnsMessage extends AbstractReferenceCounted implements DnsMessage {
-
- private static final ResourceLeakDetector leakDetector =
- new ResourceLeakDetector(DnsMessage.class);
-
- private static final int SECTION_QUESTION = DnsSection.QUESTION.ordinal();
- private static final int SECTION_COUNT = 4;
-
- private final ResourceLeak leak = leakDetector.open(this);
- private short id;
- private DnsOpCode opCode;
- private boolean recursionDesired;
- private byte z;
-
- // To reduce the memory footprint of a message,
- // each of the following fields is a single record or a list of records.
- private Object questions;
- private Object answers;
- private Object authorities;
- private Object additionals;
-
- /**
- * Creates a new instance with the specified {@code id} and {@link DnsOpCode#QUERY} opCode.
- */
- protected AbstractDnsMessage(int id) {
- this(id, DnsOpCode.QUERY);
- }
-
- /**
- * Creates a new instance with the specified {@code id} and {@code opCode}.
- */
- protected AbstractDnsMessage(int id, DnsOpCode opCode) {
- setId(id);
- setOpCode(opCode);
- }
-
- @Override
- public int id() {
- return id & 0xFFFF;
- }
-
- @Override
- public DnsMessage setId(int id) {
- this.id = (short) id;
- return this;
- }
-
- @Override
- public DnsOpCode opCode() {
- return opCode;
- }
-
- @Override
- public DnsMessage setOpCode(DnsOpCode opCode) {
- this.opCode = checkNotNull(opCode, "opCode");
- return this;
- }
-
- @Override
- public boolean isRecursionDesired() {
- return recursionDesired;
- }
-
- @Override
- public DnsMessage setRecursionDesired(boolean recursionDesired) {
- this.recursionDesired = recursionDesired;
- return this;
- }
-
- @Override
- public int z() {
- return z;
- }
-
- @Override
- public DnsMessage setZ(int z) {
- this.z = (byte) (z & 7);
- return this;
- }
-
- @Override
- public int count(DnsSection section) {
- return count(sectionOrdinal(section));
- }
-
- private int count(int section) {
- final Object records = sectionAt(section);
- if (records == null) {
- return 0;
- }
- if (records instanceof DnsRecord) {
- return 1;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return recordList.size();
- }
-
- @Override
- public int count() {
- int count = 0;
- for (int i = 0; i < SECTION_COUNT; i ++) {
- count += count(i);
- }
- return count;
- }
-
- @Override
- public T recordAt(DnsSection section) {
- return recordAt(sectionOrdinal(section));
- }
-
- private T recordAt(int section) {
- final Object records = sectionAt(section);
- if (records == null) {
- return null;
- }
-
- if (records instanceof DnsRecord) {
- return castRecord(records);
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- if (recordList.isEmpty()) {
- return null;
- }
-
- return castRecord(recordList.get(0));
- }
-
- @Override
- public T recordAt(DnsSection section, int index) {
- return recordAt(sectionOrdinal(section), index);
- }
-
- private T recordAt(int section, int index) {
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index == 0) {
- return castRecord(records);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + "' (expected: 0)");
- }
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.get(index));
- }
-
- @Override
- public DnsMessage setRecord(DnsSection section, DnsRecord record) {
- setRecord(sectionOrdinal(section), record);
- return this;
- }
-
- private void setRecord(int section, DnsRecord record) {
- clear(section);
- setSection(section, checkQuestion(section, record));
- }
-
- @Override
- public T setRecord(DnsSection section, int index, DnsRecord record) {
- return setRecord(sectionOrdinal(section), index, record);
- }
-
- private T setRecord(int section, int index, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index == 0) {
- setSection(section, record);
- return castRecord(records);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.set(index, record));
- }
-
- @Override
- public DnsMessage addRecord(DnsSection section, DnsRecord record) {
- addRecord(sectionOrdinal(section), record);
- return this;
- }
-
- private void addRecord(int section, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- setSection(section, record);
- return;
- }
-
- if (records instanceof DnsRecord) {
- final List recordList = newRecordList();
- recordList.add(castRecord(records));
- recordList.add(record);
- setSection(section, recordList);
- return;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- recordList.add(record);
- }
-
- @Override
- public DnsMessage addRecord(DnsSection section, int index, DnsRecord record) {
- addRecord(sectionOrdinal(section), index, record);
- return this;
- }
-
- private void addRecord(int section, int index, DnsRecord record) {
- checkQuestion(section, record);
-
- final Object records = sectionAt(section);
- if (records == null) {
- if (index != 0) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
-
- setSection(section, record);
- return;
- }
-
- if (records instanceof DnsRecord) {
- final List recordList;
- if (index == 0) {
- recordList = newRecordList();
- recordList.add(record);
- recordList.add(castRecord(records));
- } else if (index == 1) {
- recordList = newRecordList();
- recordList.add(castRecord(records));
- recordList.add(record);
- } else {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0 or 1)");
- }
- setSection(section, recordList);
- return;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- recordList.add(index, record);
- }
-
- @Override
- public T removeRecord(DnsSection section, int index) {
- return removeRecord(sectionOrdinal(section), index);
- }
-
- private T removeRecord(int section, int index) {
- final Object records = sectionAt(section);
- if (records == null) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
- }
-
- if (records instanceof DnsRecord) {
- if (index != 0) {
- throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
- }
-
- T record = castRecord(records);
- setSection(section, null);
- return record;
- }
-
- @SuppressWarnings("unchecked")
- final List recordList = (List) records;
- return castRecord(recordList.remove(index));
- }
-
- @Override
- public DnsMessage clear(DnsSection section) {
- clear(sectionOrdinal(section));
- return this;
- }
-
- @Override
- public DnsMessage clear() {
- for (int i = 0; i < SECTION_COUNT; i ++) {
- clear(i);
- }
- return this;
- }
-
- private void clear(int section) {
- final Object recordOrList = sectionAt(section);
- setSection(section, null);
- if (recordOrList instanceof ReferenceCounted) {
- ((ReferenceCounted) recordOrList).release();
- } else if (recordOrList instanceof List) {
- @SuppressWarnings("unchecked")
- List list = (List) recordOrList;
- if (!list.isEmpty()) {
- for (Object r : list) {
- ReferenceCountUtil.release(r);
- }
- }
- }
- }
-
- @Override
- public DnsMessage retain() {
- return (DnsMessage) super.retain();
- }
-
- @Override
- public DnsMessage retain(int increment) {
- return (DnsMessage) super.retain(increment);
- }
-
- @Override
- protected void deallocate() {
- clear();
-
- final ResourceLeak leak = this.leak;
- if (leak != null) {
- leak.close();
- }
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsMessage)) {
- return false;
- }
-
- final DnsMessage that = (DnsMessage) obj;
- if (id() != that.id()) {
- return false;
- }
-
- if (this instanceof DnsQuery) {
- if (!(that instanceof DnsQuery)) {
- return false;
- }
- } else if (that instanceof DnsQuery) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return id() * 31 + (this instanceof DnsQuery? 0 : 1);
- }
-
- private Object sectionAt(int section) {
- switch (section) {
- case 0:
- return questions;
- case 1:
- return answers;
- case 2:
- return authorities;
- case 3:
- return additionals;
- }
-
- throw new Error(); // Should never reach here.
- }
-
- private void setSection(int section, Object value) {
- switch (section) {
- case 0:
- questions = value;
- return;
- case 1:
- answers = value;
- return;
- case 2:
- authorities = value;
- return;
- case 3:
- additionals = value;
- return;
- }
-
- throw new Error(); // Should never reach here.
- }
-
- private static int sectionOrdinal(DnsSection section) {
- return checkNotNull(section, "section").ordinal();
- }
-
- private static DnsRecord checkQuestion(int section, DnsRecord record) {
- if (section == SECTION_QUESTION && !(checkNotNull(record, "record") instanceof DnsQuestion)) {
- throw new IllegalArgumentException(
- "record: " + record + " (expected: " + StringUtil.simpleClassName(DnsQuestion.class) + ')');
- }
- return record;
- }
-
- @SuppressWarnings("unchecked")
- private static T castRecord(Object record) {
- return (T) record;
- }
-
- private static ArrayList newRecordList() {
- return new ArrayList(2);
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java
deleted file mode 100644
index bf3cd685bd..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsRecord.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.util.internal.StringUtil;
-
-import java.net.IDN;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A skeletal implementation of {@link DnsRecord}.
- */
-public abstract class AbstractDnsRecord implements DnsRecord {
-
- private final String name;
- private final DnsRecordType type;
- private final short dnsClass;
- private final long timeToLive;
- private int hashCode;
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param timeToLive the TTL value of the record
- */
- protected AbstractDnsRecord(String name, DnsRecordType type, long timeToLive) {
- this(name, type, CLASS_IN, timeToLive);
- }
-
- /**
- * Creates a new record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- */
- protected AbstractDnsRecord(String name, DnsRecordType type, int dnsClass, long timeToLive) {
- if (timeToLive < 0) {
- throw new IllegalArgumentException("timeToLive: " + timeToLive + " (expected: >= 0)");
- }
- // Convert to ASCII which will also check that the length is not too big.
- // See:
- // - https://github.com/netty/netty/issues/4937
- // - https://github.com/netty/netty/issues/4935
- this.name = appendTrailingDot(IDN.toASCII(checkNotNull(name, "name")));
- this.type = checkNotNull(type, "type");
- this.dnsClass = (short) dnsClass;
- this.timeToLive = timeToLive;
- }
-
- private static String appendTrailingDot(String name) {
- if (name.length() > 0 && name.charAt(name.length() - 1) != '.') {
- return name + '.';
- }
- return name;
- }
-
- @Override
- public String name() {
- return name;
- }
-
- @Override
- public DnsRecordType type() {
- return type;
- }
-
- @Override
- public int dnsClass() {
- return dnsClass & 0xFFFF;
- }
-
- @Override
- public long timeToLive() {
- return timeToLive;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsRecord)) {
- return false;
- }
-
- final DnsRecord that = (DnsRecord) obj;
- final int hashCode = this.hashCode;
- if (hashCode != 0 && hashCode != that.hashCode()) {
- return false;
- }
-
- return type().intValue() == that.type().intValue() &&
- dnsClass() == that.dnsClass() &&
- name().equals(that.name());
- }
-
- @Override
- public int hashCode() {
- final int hashCode = this.hashCode;
- if (hashCode != 0) {
- return hashCode;
- }
-
- return this.hashCode = name.hashCode() * 31 + type().intValue() * 31 + dnsClass();
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder(64);
-
- buf.append(StringUtil.simpleClassName(this))
- .append('(')
- .append(name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type().name())
- .append(')');
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java
deleted file mode 100644
index acd4810f6c..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQuery.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-/**
- * A {@link DnsQuery} implementation for UDP/IP.
- */
-public class DatagramDnsQuery extends DefaultDnsQuery
- implements AddressedEnvelope {
-
- private final InetSocketAddress sender;
- private final InetSocketAddress recipient;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode}.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS query
- */
- public DatagramDnsQuery(
- InetSocketAddress sender, InetSocketAddress recipient, int id) {
- this(sender, recipient, id, DnsOpCode.QUERY);
- }
-
- /**
- * Creates a new instance.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS query
- * @param opCode the {@code opCode} of the DNS query
- */
- public DatagramDnsQuery(
- InetSocketAddress sender, InetSocketAddress recipient, int id, DnsOpCode opCode) {
- super(id, opCode);
-
- if (recipient == null && sender == null) {
- throw new NullPointerException("recipient and sender");
- }
-
- this.sender = sender;
- this.recipient = recipient;
- }
-
- @Override
- public DatagramDnsQuery content() {
- return this;
- }
-
- @Override
- public InetSocketAddress sender() {
- return sender;
- }
-
- @Override
- public InetSocketAddress recipient() {
- return recipient;
- }
-
- @Override
- public DatagramDnsQuery setId(int id) {
- return (DatagramDnsQuery) super.setId(id);
- }
-
- @Override
- public DatagramDnsQuery setOpCode(DnsOpCode opCode) {
- return (DatagramDnsQuery) super.setOpCode(opCode);
- }
-
- @Override
- public DatagramDnsQuery setRecursionDesired(boolean recursionDesired) {
- return (DatagramDnsQuery) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DatagramDnsQuery setZ(int z) {
- return (DatagramDnsQuery) super.setZ(z);
- }
-
- @Override
- public DatagramDnsQuery setRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsQuery) super.setRecord(section, record);
- }
-
- @Override
- public DatagramDnsQuery addRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsQuery) super.addRecord(section, record);
- }
-
- @Override
- public DatagramDnsQuery addRecord(DnsSection section, int index, DnsRecord record) {
- return (DatagramDnsQuery) super.addRecord(section, index, record);
- }
-
- @Override
- public DatagramDnsQuery clear(DnsSection section) {
- return (DatagramDnsQuery) super.clear(section);
- }
-
- @Override
- public DatagramDnsQuery clear() {
- return (DatagramDnsQuery) super.clear();
- }
-
- @Override
- public DatagramDnsQuery retain() {
- return (DatagramDnsQuery) super.retain();
- }
-
- @Override
- public DatagramDnsQuery retain(int increment) {
- return (DatagramDnsQuery) super.retain(increment);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!super.equals(obj)) {
- return false;
- }
-
- if (!(obj instanceof AddressedEnvelope)) {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- final AddressedEnvelope, SocketAddress> that = (AddressedEnvelope, SocketAddress>) obj;
- if (sender() == null) {
- if (that.sender() != null) {
- return false;
- }
- } else if (!sender().equals(that.sender())) {
- return false;
- }
-
- if (recipient() == null) {
- if (that.recipient() != null) {
- return false;
- }
- } else if (!recipient().equals(that.recipient())) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int hashCode = super.hashCode();
- if (sender() != null) {
- hashCode = hashCode * 31 + sender().hashCode();
- }
- if (recipient() != null) {
- hashCode = hashCode * 31 + recipient().hashCode();
- }
- return hashCode;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java
deleted file mode 100644
index c932075572..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryDecoder.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.MessageToMessageDecoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Decodes a {@link DatagramPacket} into a {@link DatagramDnsQuery}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsQueryDecoder extends MessageToMessageDecoder {
-
- private final DnsRecordDecoder recordDecoder;
-
- /**
- * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
- */
- public DatagramDnsQueryDecoder() {
- this(DnsRecordDecoder.DEFAULT);
- }
-
- /**
- * Creates a new decoder with the specified {@code recordDecoder}.
- */
- public DatagramDnsQueryDecoder(DnsRecordDecoder recordDecoder) {
- this.recordDecoder = checkNotNull(recordDecoder, "recordDecoder");
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) throws Exception {
- final ByteBuf buf = packet.content();
-
- final DnsQuery query = newQuery(packet, buf);
- boolean success = false;
- try {
- final int questionCount = buf.readUnsignedShort();
- final int answerCount = buf.readUnsignedShort();
- final int authorityRecordCount = buf.readUnsignedShort();
- final int additionalRecordCount = buf.readUnsignedShort();
-
- decodeQuestions(query, buf, questionCount);
- decodeRecords(query, DnsSection.ANSWER, buf, answerCount);
- decodeRecords(query, DnsSection.AUTHORITY, buf, authorityRecordCount);
- decodeRecords(query, DnsSection.ADDITIONAL, buf, additionalRecordCount);
-
- out.add(query);
- success = true;
- } finally {
- if (!success) {
- query.release();
- }
- }
- }
-
- private static DnsQuery newQuery(DatagramPacket packet, ByteBuf buf) {
- final int id = buf.readUnsignedShort();
-
- final int flags = buf.readUnsignedShort();
- if (flags >> 15 == 1) {
- throw new CorruptedFrameException("not a query");
- }
- final DnsQuery query =
- new DatagramDnsQuery(
- packet.sender(),
- packet.recipient(),
- id,
- DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)));
- query.setRecursionDesired((flags >> 8 & 1) == 1);
- query.setZ(flags >> 4 & 0x7);
- return query;
- }
-
- private void decodeQuestions(DnsQuery query, ByteBuf buf, int questionCount) throws Exception {
- for (int i = questionCount; i > 0; i--) {
- query.addRecord(DnsSection.QUESTION, recordDecoder.decodeQuestion(buf));
- }
- }
-
- private void decodeRecords(
- DnsQuery query, DnsSection section, ByteBuf buf, int count) throws Exception {
- for (int i = count; i > 0; i--) {
- final DnsRecord r = recordDecoder.decodeRecord(buf);
- if (r == null) {
- // Truncated response
- break;
- }
-
- query.addRecord(section, r);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java
deleted file mode 100644
index 8344801a45..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsQueryEncoder.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.MessageToMessageEncoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Encodes a {@link DatagramDnsQuery} (or an {@link AddressedEnvelope} of {@link DnsQuery}} into a
- * {@link DatagramPacket}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsQueryEncoder extends MessageToMessageEncoder> {
-
- private final DnsRecordEncoder recordEncoder;
-
- /**
- * Creates a new encoder with {@linkplain DnsRecordEncoder#DEFAULT the default record encoder}.
- */
- public DatagramDnsQueryEncoder() {
- this(DnsRecordEncoder.DEFAULT);
- }
-
- /**
- * Creates a new encoder with the specified {@code recordEncoder}.
- */
- public DatagramDnsQueryEncoder(DnsRecordEncoder recordEncoder) {
- this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
- }
-
- @Override
- protected void encode(
- ChannelHandlerContext ctx,
- AddressedEnvelope in, List out) throws Exception {
-
- final InetSocketAddress recipient = in.recipient();
- final DnsQuery query = in.content();
- final ByteBuf buf = allocateBuffer(ctx, in);
-
- boolean success = false;
- try {
- encodeHeader(query, buf);
- encodeQuestions(query, buf);
- encodeRecords(query, DnsSection.ADDITIONAL, buf);
- success = true;
- } finally {
- if (!success) {
- buf.release();
- }
- }
-
- out.add(new DatagramPacket(buf, recipient, null));
- }
-
- /**
- * Allocate a {@link ByteBuf} which will be used for constructing a datagram packet.
- * Sub-classes may override this method to return a {@link ByteBuf} with a perfect matching initial capacity.
- */
- protected ByteBuf allocateBuffer(
- ChannelHandlerContext ctx,
- @SuppressWarnings("unused") AddressedEnvelope msg) throws Exception {
- return ctx.alloc().ioBuffer(1024);
- }
-
- /**
- * Encodes the header that is always 12 bytes long.
- *
- * @param query the query header being encoded
- * @param buf the buffer the encoded data should be written to
- */
- private static void encodeHeader(DnsQuery query, ByteBuf buf) {
- buf.writeShort(query.id());
- int flags = 0;
- flags |= (query.opCode().byteValue() & 0xFF) << 14;
- if (query.isRecursionDesired()) {
- flags |= 1 << 8;
- }
- buf.writeShort(flags);
- buf.writeShort(query.count(DnsSection.QUESTION));
- buf.writeShort(0); // answerCount
- buf.writeShort(0); // authorityResourceCount
- buf.writeShort(query.count(DnsSection.ADDITIONAL));
- }
-
- private void encodeQuestions(DnsQuery query, ByteBuf buf) throws Exception {
- final int count = query.count(DnsSection.QUESTION);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeQuestion((DnsQuestion) query.recordAt(DnsSection.QUESTION, i), buf);
- }
- }
-
- private void encodeRecords(DnsQuery query, DnsSection section, ByteBuf buf) throws Exception {
- final int count = query.count(section);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeRecord(query.recordAt(section, i), buf);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java
deleted file mode 100644
index 0c01970eda..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponse.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-/**
- * A {@link DnsResponse} implementation for UDP/IP.
- */
-public class DatagramDnsResponse extends DefaultDnsResponse
- implements AddressedEnvelope {
-
- private final InetSocketAddress sender;
- private final InetSocketAddress recipient;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode} and
- * the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- */
- public DatagramDnsResponse(InetSocketAddress sender, InetSocketAddress recipient, int id) {
- this(sender, recipient, id, DnsOpCode.QUERY, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance with the {@link DnsResponseCode#NOERROR} responseCode.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- */
- public DatagramDnsResponse(InetSocketAddress sender, InetSocketAddress recipient, int id, DnsOpCode opCode) {
- this(sender, recipient, id, opCode, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance.
- *
- * @param sender the address of the sender
- * @param recipient the address of the recipient
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- * @param responseCode the {@code RCODE} of the DNS response
- */
- public DatagramDnsResponse(
- InetSocketAddress sender, InetSocketAddress recipient,
- int id, DnsOpCode opCode, DnsResponseCode responseCode) {
- super(id, opCode, responseCode);
-
- if (recipient == null && sender == null) {
- throw new NullPointerException("recipient and sender");
- }
-
- this.sender = sender;
- this.recipient = recipient;
- }
-
- @Override
- public DatagramDnsResponse content() {
- return this;
- }
-
- @Override
- public InetSocketAddress sender() {
- return sender;
- }
-
- @Override
- public InetSocketAddress recipient() {
- return recipient;
- }
-
- @Override
- public DatagramDnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer) {
- return (DatagramDnsResponse) super.setAuthoritativeAnswer(authoritativeAnswer);
- }
-
- @Override
- public DatagramDnsResponse setTruncated(boolean truncated) {
- return (DatagramDnsResponse) super.setTruncated(truncated);
- }
-
- @Override
- public DatagramDnsResponse setRecursionAvailable(boolean recursionAvailable) {
- return (DatagramDnsResponse) super.setRecursionAvailable(recursionAvailable);
- }
-
- @Override
- public DatagramDnsResponse setCode(DnsResponseCode code) {
- return (DatagramDnsResponse) super.setCode(code);
- }
-
- @Override
- public DatagramDnsResponse setId(int id) {
- return (DatagramDnsResponse) super.setId(id);
- }
-
- @Override
- public DatagramDnsResponse setOpCode(DnsOpCode opCode) {
- return (DatagramDnsResponse) super.setOpCode(opCode);
- }
-
- @Override
- public DatagramDnsResponse setRecursionDesired(boolean recursionDesired) {
- return (DatagramDnsResponse) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DatagramDnsResponse setZ(int z) {
- return (DatagramDnsResponse) super.setZ(z);
- }
-
- @Override
- public DatagramDnsResponse setRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsResponse) super.setRecord(section, record);
- }
-
- @Override
- public DatagramDnsResponse addRecord(DnsSection section, DnsRecord record) {
- return (DatagramDnsResponse) super.addRecord(section, record);
- }
-
- @Override
- public DatagramDnsResponse addRecord(DnsSection section, int index, DnsRecord record) {
- return (DatagramDnsResponse) super.addRecord(section, index, record);
- }
-
- @Override
- public DatagramDnsResponse clear(DnsSection section) {
- return (DatagramDnsResponse) super.clear(section);
- }
-
- @Override
- public DatagramDnsResponse clear() {
- return (DatagramDnsResponse) super.clear();
- }
-
- @Override
- public DatagramDnsResponse retain() {
- return (DatagramDnsResponse) super.retain();
- }
-
- @Override
- public DatagramDnsResponse retain(int increment) {
- return (DatagramDnsResponse) super.retain(increment);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!super.equals(obj)) {
- return false;
- }
-
- if (!(obj instanceof AddressedEnvelope)) {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- final AddressedEnvelope, SocketAddress> that = (AddressedEnvelope, SocketAddress>) obj;
- if (sender() == null) {
- if (that.sender() != null) {
- return false;
- }
- } else if (!sender().equals(that.sender())) {
- return false;
- }
-
- if (recipient() == null) {
- if (that.recipient() != null) {
- return false;
- }
- } else if (!recipient().equals(that.recipient())) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int hashCode = super.hashCode();
- if (sender() != null) {
- hashCode = hashCode * 31 + sender().hashCode();
- }
- if (recipient() != null) {
- hashCode = hashCode * 31 + recipient().hashCode();
- }
- return hashCode;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java
deleted file mode 100644
index c9e879a47f..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseDecoder.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.MessageToMessageDecoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Decodes a {@link DatagramPacket} into a {@link DatagramDnsResponse}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsResponseDecoder extends MessageToMessageDecoder {
-
- private final DnsRecordDecoder recordDecoder;
-
- /**
- * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
- */
- public DatagramDnsResponseDecoder() {
- this(DnsRecordDecoder.DEFAULT);
- }
-
- /**
- * Creates a new decoder with the specified {@code recordDecoder}.
- */
- public DatagramDnsResponseDecoder(DnsRecordDecoder recordDecoder) {
- this.recordDecoder = checkNotNull(recordDecoder, "recordDecoder");
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) throws Exception {
- final ByteBuf buf = packet.content();
-
- final DnsResponse response = newResponse(packet, buf);
- boolean success = false;
- try {
- final int questionCount = buf.readUnsignedShort();
- final int answerCount = buf.readUnsignedShort();
- final int authorityRecordCount = buf.readUnsignedShort();
- final int additionalRecordCount = buf.readUnsignedShort();
-
- decodeQuestions(response, buf, questionCount);
- decodeRecords(response, DnsSection.ANSWER, buf, answerCount);
- decodeRecords(response, DnsSection.AUTHORITY, buf, authorityRecordCount);
- decodeRecords(response, DnsSection.ADDITIONAL, buf, additionalRecordCount);
-
- out.add(response);
- success = true;
- } finally {
- if (!success) {
- response.release();
- }
- }
- }
-
- private static DnsResponse newResponse(DatagramPacket packet, ByteBuf buf) {
- final int id = buf.readUnsignedShort();
-
- final int flags = buf.readUnsignedShort();
- if (flags >> 15 == 0) {
- throw new CorruptedFrameException("not a response");
- }
-
- final DnsResponse response = new DatagramDnsResponse(
- packet.sender(),
- packet.recipient(),
- id,
- DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf)));
-
- response.setRecursionDesired((flags >> 8 & 1) == 1);
- response.setAuthoritativeAnswer((flags >> 10 & 1) == 1);
- response.setTruncated((flags >> 9 & 1) == 1);
- response.setRecursionAvailable((flags >> 7 & 1) == 1);
- response.setZ(flags >> 4 & 0x7);
- return response;
- }
-
- private void decodeQuestions(DnsResponse response, ByteBuf buf, int questionCount) throws Exception {
- for (int i = questionCount; i > 0; i --) {
- response.addRecord(DnsSection.QUESTION, recordDecoder.decodeQuestion(buf));
- }
- }
-
- private void decodeRecords(
- DnsResponse response, DnsSection section, ByteBuf buf, int count) throws Exception {
- for (int i = count; i > 0; i --) {
- final DnsRecord r = recordDecoder.decodeRecord(buf);
- if (r == null) {
- // Truncated response
- break;
- }
-
- response.addRecord(section, r);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java
deleted file mode 100644
index ac7d909156..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DatagramDnsResponseEncoder.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.MessageToMessageEncoder;
-
-import java.net.InetSocketAddress;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * Encodes a {@link DatagramDnsResponse} (or an {@link AddressedEnvelope} of {@link DnsResponse}} into a
- * {@link DatagramPacket}.
- */
-@ChannelHandler.Sharable
-public class DatagramDnsResponseEncoder
- extends MessageToMessageEncoder> {
-
- private final DnsRecordEncoder recordEncoder;
-
- /**
- * Creates a new encoder with {@linkplain DnsRecordEncoder#DEFAULT the default record encoder}.
- */
- public DatagramDnsResponseEncoder() {
- this(DnsRecordEncoder.DEFAULT);
- }
-
- /**
- * Creates a new encoder with the specified {@code recordEncoder}.
- */
- public DatagramDnsResponseEncoder(DnsRecordEncoder recordEncoder) {
- this.recordEncoder = checkNotNull(recordEncoder, "recordEncoder");
- }
-
- @Override
- protected void encode(ChannelHandlerContext ctx,
- AddressedEnvelope in, List out) throws Exception {
-
- final InetSocketAddress recipient = in.recipient();
- final DnsResponse response = in.content();
- final ByteBuf buf = allocateBuffer(ctx, in);
-
- boolean success = false;
- try {
- encodeHeader(response, buf);
- encodeQuestions(response, buf);
- encodeRecords(response, DnsSection.ANSWER, buf);
- encodeRecords(response, DnsSection.AUTHORITY, buf);
- encodeRecords(response, DnsSection.ADDITIONAL, buf);
- success = true;
- } finally {
- if (!success) {
- buf.release();
- }
- }
-
- out.add(new DatagramPacket(buf, recipient, null));
- }
-
- /**
- * Allocate a {@link ByteBuf} which will be used for constructing a datagram packet.
- * Sub-classes may override this method to return a {@link ByteBuf} with a perfect matching initial capacity.
- */
- protected ByteBuf allocateBuffer(
- ChannelHandlerContext ctx,
- @SuppressWarnings("unused") AddressedEnvelope msg) throws Exception {
- return ctx.alloc().ioBuffer(1024);
- }
-
- /**
- * Encodes the header that is always 12 bytes long.
- *
- * @param response the response header being encoded
- * @param buf the buffer the encoded data should be written to
- */
- private static void encodeHeader(DnsResponse response, ByteBuf buf) {
- buf.writeShort(response.id());
- int flags = 32768;
- flags |= (response.opCode().byteValue() & 0xFF) << 11;
- if (response.isAuthoritativeAnswer()) {
- flags |= 1 << 10;
- }
- if (response.isTruncated()) {
- flags |= 1 << 9;
- }
- if (response.isRecursionDesired()) {
- flags |= 1 << 8;
- }
- if (response.isRecursionAvailable()) {
- flags |= 1 << 7;
- }
- flags |= response.z() << 4;
- flags |= response.code().intValue();
- buf.writeShort(flags);
- buf.writeShort(response.count(DnsSection.QUESTION));
- buf.writeShort(response.count(DnsSection.ANSWER));
- buf.writeShort(response.count(DnsSection.AUTHORITY));
- buf.writeShort(response.count(DnsSection.ADDITIONAL));
- }
-
- private void encodeQuestions(DnsResponse response, ByteBuf buf) throws Exception {
- final int count = response.count(DnsSection.QUESTION);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeQuestion((DnsQuestion) response.recordAt(DnsSection.QUESTION, i), buf);
- }
- }
-
- private void encodeRecords(DnsResponse response, DnsSection section, ByteBuf buf) throws Exception {
- final int count = response.count(section);
- for (int i = 0; i < count; i++) {
- recordEncoder.encodeRecord(response.recordAt(section, i), buf);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java
deleted file mode 100644
index 517c5f9570..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsPtrRecord.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-import io.netty.util.internal.StringUtil;
-
-public class DefaultDnsPtrRecord extends AbstractDnsRecord implements DnsPtrRecord {
-
- private final String hostname;
-
- /**
- * Creates a new PTR record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- * @param hostname the hostname this PTR record resolves to.
- */
- public DefaultDnsPtrRecord(
- String name, int dnsClass, long timeToLive, String hostname) {
- super(name, DnsRecordType.PTR, dnsClass, timeToLive);
- this.hostname = checkNotNull(hostname, "hostname");
- }
-
- @Override
- public String hostname() {
- return hostname;
- }
-
- @Override
- public String toString() {
- final StringBuilder buf = new StringBuilder(64).append(StringUtil.simpleClassName(this)).append('(');
- final DnsRecordType type = type();
- buf.append(name().isEmpty()? "" : name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type.name());
-
- buf.append(' ')
- .append(hostname);
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java
deleted file mode 100644
index 93920ad8f0..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuery.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * The default {@link DnsQuery} implementation.
- */
-public class DefaultDnsQuery extends AbstractDnsMessage implements DnsQuery {
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode}.
- *
- * @param id the {@code ID} of the DNS query
- */
- public DefaultDnsQuery(int id) {
- super(id);
- }
-
- /**
- * Creates a new instance.
- *
- * @param id the {@code ID} of the DNS query
- * @param opCode the {@code opCode} of the DNS query
- */
- public DefaultDnsQuery(int id, DnsOpCode opCode) {
- super(id, opCode);
- }
-
- @Override
- public DnsQuery setId(int id) {
- return (DnsQuery) super.setId(id);
- }
-
- @Override
- public DnsQuery setOpCode(DnsOpCode opCode) {
- return (DnsQuery) super.setOpCode(opCode);
- }
-
- @Override
- public DnsQuery setRecursionDesired(boolean recursionDesired) {
- return (DnsQuery) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DnsQuery setZ(int z) {
- return (DnsQuery) super.setZ(z);
- }
-
- @Override
- public DnsQuery setRecord(DnsSection section, DnsRecord record) {
- return (DnsQuery) super.setRecord(section, record);
- }
-
- @Override
- public DnsQuery addRecord(DnsSection section, DnsRecord record) {
- return (DnsQuery) super.addRecord(section, record);
- }
-
- @Override
- public DnsQuery addRecord(DnsSection section, int index, DnsRecord record) {
- return (DnsQuery) super.addRecord(section, index, record);
- }
-
- @Override
- public DnsQuery clear(DnsSection section) {
- return (DnsQuery) super.clear(section);
- }
-
- @Override
- public DnsQuery clear() {
- return (DnsQuery) super.clear();
- }
-
- @Override
- public DnsQuery retain() {
- return (DnsQuery) super.retain();
- }
-
- @Override
- public DnsQuery retain(int increment) {
- return (DnsQuery) super.retain(increment);
- }
-
- @Override
- public String toString() {
- return DnsMessageUtil.appendQuery(new StringBuilder(128), this).toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java
deleted file mode 100644
index 09ceb1e62c..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsQuestion.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.util.internal.StringUtil;
-
-/**
- * The default {@link DnsQuestion} implementation.
- */
-public class DefaultDnsQuestion extends AbstractDnsRecord implements DnsQuestion {
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} question.
- *
- * @param name the domain name of the DNS question
- * @param type the type of the DNS question
- */
- public DefaultDnsQuestion(String name, DnsRecordType type) {
- super(name, type, 0);
- }
-
- /**
- * Creates a new question.
- *
- * @param name the domain name of the DNS question
- * @param type the type of the DNS question
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- */
- public DefaultDnsQuestion(String name, DnsRecordType type, int dnsClass) {
- super(name, type, dnsClass, 0);
- }
-
- @Override
- public String toString() {
- StringBuilder buf = new StringBuilder(64);
-
- buf.append(StringUtil.simpleClassName(this))
- .append('(')
- .append(name())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type().name())
- .append(')');
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java
deleted file mode 100644
index f37b7ba880..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRawRecord.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.util.internal.StringUtil;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The default {@code DnsRawRecord} implementation.
- */
-public class DefaultDnsRawRecord extends AbstractDnsRecord implements DnsRawRecord {
-
- private final ByteBuf content;
-
- /**
- * Creates a new {@link #CLASS_IN IN-class} record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param timeToLive the TTL value of the record
- */
- public DefaultDnsRawRecord(String name, DnsRecordType type, long timeToLive, ByteBuf content) {
- this(name, type, DnsRecord.CLASS_IN, timeToLive, content);
- }
-
- /**
- * Creates a new record.
- *
- * @param name the domain name
- * @param type the type of the record
- * @param dnsClass the class of the record, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- * @param timeToLive the TTL value of the record
- */
- public DefaultDnsRawRecord(
- String name, DnsRecordType type, int dnsClass, long timeToLive, ByteBuf content) {
- super(name, type, dnsClass, timeToLive);
- this.content = checkNotNull(content, "content");
- }
-
- @Override
- public ByteBuf content() {
- return content;
- }
-
- @Override
- public DnsRawRecord copy() {
- return new DefaultDnsRawRecord(name(), type(), dnsClass(), timeToLive(), content().copy());
- }
-
- @Override
- public DnsRawRecord duplicate() {
- return new DefaultDnsRawRecord(name(), type(), dnsClass(), timeToLive(), content().duplicate());
- }
-
- @Override
- public int refCnt() {
- return content().refCnt();
- }
-
- @Override
- public DnsRawRecord retain() {
- content().retain();
- return this;
- }
-
- @Override
- public DnsRawRecord retain(int increment) {
- content().retain(increment);
- return this;
- }
-
- @Override
- public boolean release() {
- return content().release();
- }
-
- @Override
- public boolean release(int decrement) {
- return content().release(decrement);
- }
-
- @Override
- public String toString() {
- final StringBuilder buf = new StringBuilder(64).append(StringUtil.simpleClassName(this)).append('(');
- final DnsRecordType type = type();
- if (type != DnsRecordType.OPT) {
- buf.append(name().isEmpty()? "" : name())
- .append(' ')
- .append(timeToLive())
- .append(' ');
-
- DnsMessageUtil.appendRecordClass(buf, dnsClass())
- .append(' ')
- .append(type.name());
- } else {
- buf.append("OPT flags:")
- .append(timeToLive())
- .append(" udp:")
- .append(dnsClass());
- }
-
- buf.append(' ')
- .append(content().readableBytes())
- .append("B)");
-
- return buf.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java
deleted file mode 100644
index 1a733f437d..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.util.CharsetUtil;
-
-/**
- * The default {@link DnsRecordDecoder} implementation.
- *
- * @see DefaultDnsRecordEncoder
- */
-public class DefaultDnsRecordDecoder implements DnsRecordDecoder {
-
- static final String ROOT = ".";
-
- /**
- * Creates a new instance.
- */
- protected DefaultDnsRecordDecoder() { }
-
- @Override
- public final DnsQuestion decodeQuestion(ByteBuf in) throws Exception {
- String name = decodeName(in);
- DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
- int qClass = in.readUnsignedShort();
- return new DefaultDnsQuestion(name, type, qClass);
- }
-
- @Override
- public final T decodeRecord(ByteBuf in) throws Exception {
- final int startOffset = in.readerIndex();
- final String name = decodeName(in);
-
- final int endOffset = in.writerIndex();
- if (endOffset - startOffset < 10) {
- // Not enough data
- in.readerIndex(startOffset);
- return null;
- }
-
- final DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort());
- final int aClass = in.readUnsignedShort();
- final long ttl = in.readUnsignedInt();
- final int length = in.readUnsignedShort();
- final int offset = in.readerIndex();
-
- if (endOffset - offset < length) {
- // Not enough data
- in.readerIndex(startOffset);
- return null;
- }
-
- @SuppressWarnings("unchecked")
- T record = (T) decodeRecord(name, type, aClass, ttl, in, offset, length);
- in.readerIndex(offset + length);
- return record;
- }
-
- /**
- * Decodes a record from the information decoded so far by {@link #decodeRecord(ByteBuf)}.
- *
- * @param name the domain name of the record
- * @param type the type of the record
- * @param dnsClass the class of the record
- * @param timeToLive the TTL of the record
- * @param in the {@link ByteBuf} that contains the RDATA
- * @param offset the start offset of the RDATA in {@code in}
- * @param length the length of the RDATA
- *
- * @return a {@link DnsRawRecord}. Override this method to decode RDATA and return other record implementation.
- */
- protected DnsRecord decodeRecord(
- String name, DnsRecordType type, int dnsClass, long timeToLive,
- ByteBuf in, int offset, int length) throws Exception {
-
- // DNS message compression means that domain names may contain "pointers" to other positions in the packet
- // to build a full message. This means the indexes are meaningful and we need the ability to reference the
- // indexes un-obstructed, and thus we cannot use a slice here.
- // See https://www.ietf.org/rfc/rfc1035 [4.1.4. Message compression]
- if (type == DnsRecordType.PTR) {
- in.setIndex(offset, offset + length);
- return new DefaultDnsPtrRecord(
- name, dnsClass, timeToLive, decodeName0(in.duplicate().setIndex(offset, offset + length)));
- }
- return new DefaultDnsRawRecord(
- name, type, dnsClass, timeToLive, in.duplicate().setIndex(offset, offset + length).retain());
- }
-
- /**
- * Retrieves a domain name given a buffer containing a DNS packet. If the
- * name contains a pointer, the position of the buffer will be set to
- * directly after the pointer's index after the name has been read.
- *
- * @param in the byte buffer containing the DNS packet
- * @return the domain name for an entry
- */
- protected String decodeName0(ByteBuf in) {
- return decodeName(in);
- }
-
- /**
- * Retrieves a domain name given a buffer containing a DNS packet. If the
- * name contains a pointer, the position of the buffer will be set to
- * directly after the pointer's index after the name has been read.
- *
- * @param in the byte buffer containing the DNS packet
- * @return the domain name for an entry
- */
- public static String decodeName(ByteBuf in) {
- int position = -1;
- int checked = 0;
- final int end = in.writerIndex();
- final int readable = in.readableBytes();
-
- // Looking at the spec we should always have at least enough readable bytes to read a byte here but it seems
- // some servers do not respect this for empty names. So just workaround this and return an empty name in this
- // case.
- //
- // See:
- // - https://github.com/netty/netty/issues/5014
- // - https://www.ietf.org/rfc/rfc1035.txt , Section 3.1
- if (readable == 0) {
- return ROOT;
- }
-
- final StringBuilder name = new StringBuilder(readable << 1);
- while (in.isReadable()) {
- final int len = in.readUnsignedByte();
- final boolean pointer = (len & 0xc0) == 0xc0;
- if (pointer) {
- if (position == -1) {
- position = in.readerIndex() + 1;
- }
-
- if (!in.isReadable()) {
- throw new CorruptedFrameException("truncated pointer in a name");
- }
-
- final int next = (len & 0x3f) << 8 | in.readUnsignedByte();
- if (next >= end) {
- throw new CorruptedFrameException("name has an out-of-range pointer");
- }
- in.readerIndex(next);
-
- // check for loops
- checked += 2;
- if (checked >= end) {
- throw new CorruptedFrameException("name contains a loop.");
- }
- } else if (len != 0) {
- if (!in.isReadable(len)) {
- throw new CorruptedFrameException("truncated label in a name");
- }
- name.append(in.toString(in.readerIndex(), len, CharsetUtil.UTF_8)).append('.');
- in.skipBytes(len);
- } else { // len == 0
- break;
- }
- }
-
- if (position != -1) {
- in.readerIndex(position);
- }
-
- if (name.length() == 0) {
- return ROOT;
- }
-
- if (name.charAt(name.length() - 1) != '.') {
- name.append('.');
- }
-
- return name.toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
deleted file mode 100644
index 2eb61a4444..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoder.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufUtil;
-import io.netty.handler.codec.UnsupportedMessageTypeException;
-import io.netty.util.internal.StringUtil;
-
-import static io.netty.handler.codec.dns.DefaultDnsRecordDecoder.ROOT;
-
-/**
- * The default {@link DnsRecordEncoder} implementation.
- *
- * @see DefaultDnsRecordDecoder
- */
-public class DefaultDnsRecordEncoder implements DnsRecordEncoder {
-
- /**
- * Creates a new instance.
- */
- protected DefaultDnsRecordEncoder() { }
-
- @Override
- public final void encodeQuestion(DnsQuestion question, ByteBuf out) throws Exception {
- encodeName(question.name(), out);
- out.writeShort(question.type().intValue());
- out.writeShort(question.dnsClass());
- }
-
- @Override
- public void encodeRecord(DnsRecord record, ByteBuf out) throws Exception {
- if (record instanceof DnsQuestion) {
- encodeQuestion((DnsQuestion) record, out);
- } else if (record instanceof DnsPtrRecord) {
- encodePtrRecord((DnsPtrRecord) record, out);
- } else if (record instanceof DnsRawRecord) {
- encodeRawRecord((DnsRawRecord) record, out);
- } else {
- throw new UnsupportedMessageTypeException(StringUtil.simpleClassName(record));
- }
- }
-
- private void encodePtrRecord(DnsPtrRecord record, ByteBuf out) throws Exception {
- encodeName(record.name(), out);
-
- out.writeShort(record.type().intValue());
- out.writeShort(record.dnsClass());
- out.writeInt((int) record.timeToLive());
-
- encodeName(record.hostname(), out);
- }
-
- private void encodeRawRecord(DnsRawRecord record, ByteBuf out) throws Exception {
- encodeName(record.name(), out);
-
- out.writeShort(record.type().intValue());
- out.writeShort(record.dnsClass());
- out.writeInt((int) record.timeToLive());
-
- ByteBuf content = record.content();
- int contentLen = content.readableBytes();
-
- out.writeShort(contentLen);
- out.writeBytes(content, content.readerIndex(), contentLen);
- }
-
- protected void encodeName(String name, ByteBuf buf) throws Exception {
- if (ROOT.equals(name)) {
- // Root domain
- buf.writeByte(0);
- return;
- }
-
- final String[] labels = name.split("\\.");
- for (String label : labels) {
- final int labelLen = label.length();
- if (labelLen == 0) {
- // zero-length label means the end of the name.
- break;
- }
-
- buf.writeByte(labelLen);
- ByteBufUtil.writeAscii(buf, label);
- }
-
- buf.writeByte(0); // marks end of name field
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java
deleted file mode 100644
index 5832aa755a..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsResponse.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The default {@link DnsResponse} implementation.
- */
-public class DefaultDnsResponse extends AbstractDnsMessage implements DnsResponse {
-
- private boolean authoritativeAnswer;
- private boolean truncated;
- private boolean recursionAvailable;
- private DnsResponseCode code;
-
- /**
- * Creates a new instance with the {@link DnsOpCode#QUERY} {@code opCode} and
- * the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param id the {@code ID} of the DNS response
- */
- public DefaultDnsResponse(int id) {
- this(id, DnsOpCode.QUERY, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance with the {@link DnsResponseCode#NOERROR} {@code RCODE}.
- *
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- */
- public DefaultDnsResponse(int id, DnsOpCode opCode) {
- this(id, opCode, DnsResponseCode.NOERROR);
- }
-
- /**
- * Creates a new instance.
- *
- * @param id the {@code ID} of the DNS response
- * @param opCode the {@code opCode} of the DNS response
- * @param code the {@code RCODE} of the DNS response
- */
- public DefaultDnsResponse(int id, DnsOpCode opCode, DnsResponseCode code) {
- super(id, opCode);
- setCode(code);
- }
-
- @Override
- public boolean isAuthoritativeAnswer() {
- return authoritativeAnswer;
- }
-
- @Override
- public DnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer) {
- this.authoritativeAnswer = authoritativeAnswer;
- return this;
- }
-
- @Override
- public boolean isTruncated() {
- return truncated;
- }
-
- @Override
- public DnsResponse setTruncated(boolean truncated) {
- this.truncated = truncated;
- return this;
- }
-
- @Override
- public boolean isRecursionAvailable() {
- return recursionAvailable;
- }
-
- @Override
- public DnsResponse setRecursionAvailable(boolean recursionAvailable) {
- this.recursionAvailable = recursionAvailable;
- return this;
- }
-
- @Override
- public DnsResponseCode code() {
- return code;
- }
-
- @Override
- public DnsResponse setCode(DnsResponseCode code) {
- this.code = checkNotNull(code, "code");
- return this;
- }
-
- @Override
- public DnsResponse setId(int id) {
- return (DnsResponse) super.setId(id);
- }
-
- @Override
- public DnsResponse setOpCode(DnsOpCode opCode) {
- return (DnsResponse) super.setOpCode(opCode);
- }
-
- @Override
- public DnsResponse setRecursionDesired(boolean recursionDesired) {
- return (DnsResponse) super.setRecursionDesired(recursionDesired);
- }
-
- @Override
- public DnsResponse setZ(int z) {
- return (DnsResponse) super.setZ(z);
- }
-
- @Override
- public DnsResponse setRecord(DnsSection section, DnsRecord record) {
- return (DnsResponse) super.setRecord(section, record);
- }
-
- @Override
- public DnsResponse addRecord(DnsSection section, DnsRecord record) {
- return (DnsResponse) super.addRecord(section, record);
- }
-
- @Override
- public DnsResponse addRecord(DnsSection section, int index, DnsRecord record) {
- return (DnsResponse) super.addRecord(section, index, record);
- }
-
- @Override
- public DnsResponse clear(DnsSection section) {
- return (DnsResponse) super.clear(section);
- }
-
- @Override
- public DnsResponse clear() {
- return (DnsResponse) super.clear();
- }
-
- @Override
- public DnsResponse retain() {
- return (DnsResponse) super.retain();
- }
-
- @Override
- public DnsResponse retain(int increment) {
- return (DnsResponse) super.retain(increment);
- }
-
- @Override
- public String toString() {
- return DnsMessageUtil.appendResponse(new StringBuilder(128), this).toString();
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java
deleted file mode 100644
index 268e56a2b6..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessage.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.util.ReferenceCounted;
-
-/**
- * The superclass which contains core information concerning a {@link DnsQuery} and a {@link DnsResponse}.
- */
-public interface DnsMessage extends ReferenceCounted {
-
- /**
- * Returns the {@code ID} of this DNS message.
- */
- int id();
-
- /**
- * Sets the {@code ID} of this DNS message.
- */
- DnsMessage setId(int id);
-
- /**
- * Returns the {@code opCode} of this DNS message.
- */
- DnsOpCode opCode();
-
- /**
- * Sets the {@code opCode} of this DNS message.
- */
- DnsMessage setOpCode(DnsOpCode opCode);
-
- /**
- * Returns the {@code RD} (recursion desired} field of this DNS message.
- */
- boolean isRecursionDesired();
-
- /**
- * Sets the {@code RD} (recursion desired} field of this DNS message.
- */
- DnsMessage setRecursionDesired(boolean recursionDesired);
-
- /**
- * Returns the {@code Z} (reserved for future use) field of this DNS message.
- */
- int z();
-
- /**
- * Sets the {@code Z} (reserved for future use) field of this DNS message.
- */
- DnsMessage setZ(int z);
-
- /**
- * Returns the number of records in the specified {@code section} of this DNS message.
- */
- int count(DnsSection section);
-
- /**
- * Returns the number of records in this DNS message.
- */
- int count();
-
- /**
- * Returns the first record in the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @return {@code null} if this message doesn't have any records in the specified {@code section}
- */
- T recordAt(DnsSection section);
-
- /**
- * Returns the record at the specified {@code index} of the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- T recordAt(DnsSection section, int index);
-
- /**
- * Sets the specified {@code section} of this DNS message to the specified {@code record},
- * making it a single-record section. When the specified {@code section} is {@link DnsSection#QUESTION},
- * the specified {@code record} must be a {@link DnsQuestion}.
- */
- DnsMessage setRecord(DnsSection section, DnsRecord record);
-
- /**
- * Sets the specified {@code record} at the specified {@code index} of the specified {@code section}
- * of this DNS message. When the specified {@code section} is {@link DnsSection#QUESTION},
- * the specified {@code record} must be a {@link DnsQuestion}.
- *
- * @return the old record
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- T setRecord(DnsSection section, int index, DnsRecord record);
-
- /**
- * Adds the specified {@code record} at the end of the specified {@code section} of this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the specified {@code record}
- * must be a {@link DnsQuestion}.
- */
- DnsMessage addRecord(DnsSection section, DnsRecord record);
-
- /**
- * Adds the specified {@code record} at the specified {@code index} of the specified {@code section}
- * of this DNS message. When the specified {@code section} is {@link DnsSection#QUESTION}, the specified
- * {@code record} must be a {@link DnsQuestion}.
- *
- * @throws IndexOutOfBoundsException if the specified {@code index} is out of bounds
- */
- DnsMessage addRecord(DnsSection section, int index, DnsRecord record);
-
- /**
- * Removes the record at the specified {@code index} of the specified {@code section} from this DNS message.
- * When the specified {@code section} is {@link DnsSection#QUESTION}, the type of the returned record is
- * always {@link DnsQuestion}.
- *
- * @return the removed record
- */
- T removeRecord(DnsSection section, int index);
-
- /**
- * Removes all the records in the specified {@code section} of this DNS message.
- */
- DnsMessage clear(DnsSection section);
-
- /**
- * Removes all the records in this DNS message.
- */
- DnsMessage clear();
-
- @Override
- DnsMessage retain();
-
- @Override
- DnsMessage retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java
deleted file mode 100644
index 8a059949d8..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsMessageUtil.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.channel.AddressedEnvelope;
-import io.netty.util.internal.StringUtil;
-
-import java.net.SocketAddress;
-
-/**
- * Provides some utility methods for DNS message implementations.
- */
-final class DnsMessageUtil {
-
- static StringBuilder appendQuery(StringBuilder buf, DnsQuery query) {
- appendQueryHeader(buf, query);
- appendAllRecords(buf, query);
- return buf;
- }
-
- static StringBuilder appendResponse(StringBuilder buf, DnsResponse response) {
- appendResponseHeader(buf, response);
- appendAllRecords(buf, response);
- return buf;
- }
-
- static StringBuilder appendRecordClass(StringBuilder buf, int dnsClass) {
- final String name;
- switch (dnsClass &= 0xFFFF) {
- case DnsRecord.CLASS_IN:
- name = "IN";
- break;
- case DnsRecord.CLASS_CSNET:
- name = "CSNET";
- break;
- case DnsRecord.CLASS_CHAOS:
- name = "CHAOS";
- break;
- case DnsRecord.CLASS_HESIOD:
- name = "HESIOD";
- break;
- case DnsRecord.CLASS_NONE:
- name = "NONE";
- break;
- case DnsRecord.CLASS_ANY:
- name = "ANY";
- break;
- default:
- name = null;
- break;
- }
-
- if (name != null) {
- buf.append(name);
- } else {
- buf.append("UNKNOWN(").append(dnsClass).append(')');
- }
-
- return buf;
- }
-
- private static void appendQueryHeader(StringBuilder buf, DnsQuery msg) {
- buf.append(StringUtil.simpleClassName(msg))
- .append('(');
-
- appendAddresses(buf, msg)
- .append(msg.id())
- .append(", ")
- .append(msg.opCode());
-
- if (msg.isRecursionDesired()) {
- buf.append(", RD");
- }
- if (msg.z() != 0) {
- buf.append(", Z: ")
- .append(msg.z());
- }
- buf.append(')');
- }
-
- private static void appendResponseHeader(StringBuilder buf, DnsResponse msg) {
- buf.append(StringUtil.simpleClassName(msg))
- .append('(');
-
- appendAddresses(buf, msg)
- .append(msg.id())
- .append(", ")
- .append(msg.opCode())
- .append(", ")
- .append(msg.code())
- .append(',');
-
- boolean hasComma = true;
- if (msg.isRecursionDesired()) {
- hasComma = false;
- buf.append(" RD");
- }
- if (msg.isAuthoritativeAnswer()) {
- hasComma = false;
- buf.append(" AA");
- }
- if (msg.isTruncated()) {
- hasComma = false;
- buf.append(" TC");
- }
- if (msg.isRecursionAvailable()) {
- hasComma = false;
- buf.append(" RA");
- }
- if (msg.z() != 0) {
- if (!hasComma) {
- buf.append(',');
- }
- buf.append(" Z: ")
- .append(msg.z());
- }
-
- if (hasComma) {
- buf.setCharAt(buf.length() - 1, ')');
- } else {
- buf.append(')');
- }
- }
-
- private static StringBuilder appendAddresses(StringBuilder buf, DnsMessage msg) {
-
- if (!(msg instanceof AddressedEnvelope)) {
- return buf;
- }
-
- @SuppressWarnings("unchecked")
- AddressedEnvelope, SocketAddress> envelope = (AddressedEnvelope, SocketAddress>) msg;
-
- SocketAddress addr = envelope.sender();
- if (addr != null) {
- buf.append("from: ")
- .append(addr)
- .append(", ");
- }
-
- addr = envelope.recipient();
- if (addr != null) {
- buf.append("to: ")
- .append(addr)
- .append(", ");
- }
-
- return buf;
- }
-
- private static void appendAllRecords(StringBuilder buf, DnsMessage msg) {
- appendRecords(buf, msg, DnsSection.QUESTION);
- appendRecords(buf, msg, DnsSection.ANSWER);
- appendRecords(buf, msg, DnsSection.AUTHORITY);
- appendRecords(buf, msg, DnsSection.ADDITIONAL);
- }
-
- private static void appendRecords(StringBuilder buf, DnsMessage message, DnsSection section) {
- final int count = message.count(section);
- for (int i = 0; i < count; i ++) {
- buf.append(StringUtil.NEWLINE)
- .append('\t')
- .append(message.recordAt(section, i));
- }
- }
-
- private DnsMessageUtil() { }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java
deleted file mode 100644
index 4140b2e3ff..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsOpCode.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The DNS {@code OpCode} as defined in RFC2929.
- */
-public class DnsOpCode implements Comparable {
-
- /**
- * The 'Query' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode QUERY = new DnsOpCode(0x00, "QUERY");
-
- /**
- * The 'IQuery' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode IQUERY = new DnsOpCode(0x01, "IQUERY");
-
- /**
- * The 'Status' DNS OpCode, as defined in RFC1035.
- */
- public static final DnsOpCode STATUS = new DnsOpCode(0x02, "STATUS");
-
- /**
- * The 'Notify' DNS OpCode, as defined in RFC1996.
- */
- public static final DnsOpCode NOTIFY = new DnsOpCode(0x04, "NOTIFY");
-
- /**
- * The 'Update' DNS OpCode, as defined in RFC2136.
- */
- public static final DnsOpCode UPDATE = new DnsOpCode(0x05, "UPDATE");
-
- /**
- * Returns the {@link DnsOpCode} instance of the specified byte value.
- */
- public static DnsOpCode valueOf(int b) {
- switch (b) {
- case 0x00:
- return QUERY;
- case 0x01:
- return IQUERY;
- case 0x02:
- return STATUS;
- case 0x04:
- return NOTIFY;
- case 0x05:
- return UPDATE;
- }
-
- return new DnsOpCode(b);
- }
-
- private final byte byteValue;
- private final String name;
- private String text;
-
- private DnsOpCode(int byteValue) {
- this(byteValue, "UNKNOWN");
- }
-
- public DnsOpCode(int byteValue, String name) {
- this.byteValue = (byte) byteValue;
- this.name = checkNotNull(name, "name");
- }
-
- public byte byteValue() {
- return byteValue;
- }
-
- @Override
- public int hashCode() {
- return byteValue;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof DnsOpCode)) {
- return false;
- }
-
- return byteValue == ((DnsOpCode) obj).byteValue;
- }
-
- @Override
- public int compareTo(DnsOpCode o) {
- return byteValue - o.byteValue;
- }
-
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + (byteValue & 0xFF) + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java
deleted file mode 100644
index 53962e1142..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsPtrRecord.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-public interface DnsPtrRecord extends DnsRecord {
-
- /**
- * Returns the hostname this PTR record resolves to.
- */
- String hostname();
-
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java
deleted file mode 100644
index 28de3d2a86..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuery.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * A DNS query message.
- */
-public interface DnsQuery extends DnsMessage {
- @Override
- DnsQuery setId(int id);
-
- @Override
- DnsQuery setOpCode(DnsOpCode opCode);
-
- @Override
- DnsQuery setRecursionDesired(boolean recursionDesired);
-
- @Override
- DnsQuery setZ(int z);
-
- @Override
- DnsQuery setRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsQuery addRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsQuery addRecord(DnsSection section, int index, DnsRecord record);
-
- @Override
- DnsQuery clear(DnsSection section);
-
- @Override
- DnsQuery clear();
-
- @Override
- DnsQuery retain();
-
- @Override
- DnsQuery retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java
deleted file mode 100644
index 082ca3a11b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsQuestion.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * A DNS question.
- */
-public interface DnsQuestion extends DnsRecord {
- /**
- * An unused property. This method will always return {@code 0}.
- */
- @Override
- long timeToLive();
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java
deleted file mode 100644
index eb96dee270..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRawRecord.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBufHolder;
-
-/**
- * A generic {@link DnsRecord} that contains an undecoded {@code RDATA}.
- */
-public interface DnsRawRecord extends DnsRecord, ByteBufHolder {
- @Override
- DnsRawRecord copy();
-
- @Override
- DnsRawRecord duplicate();
-
- @Override
- DnsRawRecord retain();
-
- @Override
- DnsRawRecord retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java
deleted file mode 100644
index eb1c060498..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecord.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * A DNS resource record.
- */
-public interface DnsRecord {
-
- /**
- * DNS resource record class: {@code IN}
- */
- int CLASS_IN = 0x0001;
-
- /**
- * DNS resource record class: {@code CSNET}
- */
- int CLASS_CSNET = 0x0002;
-
- /**
- * DNS resource record class: {@code CHAOS}
- */
- int CLASS_CHAOS = 0x0003;
-
- /**
- * DNS resource record class: {@code HESIOD}
- */
- int CLASS_HESIOD = 0x0004;
-
- /**
- * DNS resource record class: {@code NONE}
- */
- int CLASS_NONE = 0x00fe;
-
- /**
- * DNS resource record class: {@code ANY}
- */
- int CLASS_ANY = 0x00ff;
-
- /**
- * Returns the name of this resource record.
- */
- String name();
-
- /**
- * Returns the type of this resource record.
- */
- DnsRecordType type();
-
- /**
- * Returns the class of this resource record.
- *
- * @return the class value, usually one of the following:
- *
- *
{@link #CLASS_IN}
- *
{@link #CLASS_CSNET}
- *
{@link #CLASS_CHAOS}
- *
{@link #CLASS_HESIOD}
- *
{@link #CLASS_NONE}
- *
{@link #CLASS_ANY}
- *
- */
- int dnsClass();
-
- /**
- * Returns the time to live after reading for this resource record.
- */
- long timeToLive();
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java
deleted file mode 100644
index a2b6315acc..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordDecoder.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-
-/**
- * Decodes a DNS record into its object representation.
- *
- * @see DatagramDnsResponseDecoder
- */
-public interface DnsRecordDecoder {
-
- DnsRecordDecoder DEFAULT = new DefaultDnsRecordDecoder();
-
- /**
- * Decodes a DNS question into its object representation.
- *
- * @param in the input buffer which contains a DNS question at its reader index
- */
- DnsQuestion decodeQuestion(ByteBuf in) throws Exception;
-
- /**
- * Decodes a DNS record into its object representation.
- *
- * @param in the input buffer which contains a DNS record at its reader index
- *
- * @return the decoded record, or {@code null} if there are not enough data in the input buffer
- */
- T decodeRecord(ByteBuf in) throws Exception;
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java
deleted file mode 100644
index 56b7fa1a05..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordEncoder.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-
-/**
- * Encodes a {@link DnsRecord} into binary representation.
- *
- * @see DatagramDnsQueryEncoder
- */
-public interface DnsRecordEncoder {
-
- DnsRecordEncoder DEFAULT = new DefaultDnsRecordEncoder();
-
- /**
- * Encodes a {@link DnsQuestion}.
- *
- * @param out the output buffer where the encoded question will be written to
- */
- void encodeQuestion(DnsQuestion question, ByteBuf out) throws Exception;
-
- /**
- * Encodes a {@link DnsRecord}.
- *
- * @param out the output buffer where the encoded record will be written to
- */
- void encodeRecord(DnsRecord record, ByteBuf out) throws Exception;
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java
deleted file mode 100644
index 77f3d3c5a6..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsRecordType.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.util.collection.IntObjectHashMap;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Represents a DNS record type.
- */
-public class DnsRecordType implements Comparable {
-
- /**
- * Address record RFC 1035 Returns a 32-bit IPv4 address, most commonly used
- * to map hostnames to an IP address of the host, but also used for DNSBLs,
- * storing subnet masks in RFC 1101, etc.
- */
- public static final DnsRecordType A = new DnsRecordType(0x0001, "A");
-
- /**
- * Name server record RFC 1035 Delegates a DNS zone to use the given
- * authoritative name servers
- */
- public static final DnsRecordType NS = new DnsRecordType(0x0002, "NS");
-
- /**
- * Canonical name record RFC 1035 Alias of one name to another: the DNS
- * lookup will continue by retrying the lookup with the new name.
- */
- public static final DnsRecordType CNAME = new DnsRecordType(0x0005, "CNAME");
-
- /**
- * Start of [a zone of] authority record RFC 1035 and RFC 2308 Specifies
- * authoritative information about a DNS zone, including the primary name
- * server, the email of the domain administrator, the domain serial number,
- * and several timers relating to refreshing the zone.
- */
- public static final DnsRecordType SOA = new DnsRecordType(0x0006, "SOA");
-
- /**
- * Pointer record RFC 1035 Pointer to a canonical name. Unlike a CNAME, DNS
- * processing does NOT proceed, just the name is returned. The most common
- * use is for implementing reverse DNS lookups, but other uses include such
- * things as DNS-SD.
- */
- public static final DnsRecordType PTR = new DnsRecordType(0x000c, "PTR");
-
- /**
- * Mail exchange record RFC 1035 Maps a domain name to a list of message
- * transfer agents for that domain.
- */
- public static final DnsRecordType MX = new DnsRecordType(0x000f, "MX");
-
- /**
- * Text record RFC 1035 Originally for arbitrary human-readable text in a
- * DNS record. Since the early 1990s, however, this record more often
- * carries machine-readable data, such as specified by RFC 1464,
- * opportunistic encryption, Sender Policy Framework, DKIM, DMARC DNS-SD,
- * etc.
- */
- public static final DnsRecordType TXT = new DnsRecordType(0x0010, "TXT");
-
- /**
- * Responsible person record RFC 1183 Information about the responsible
- * person(s) for the domain. Usually an email address with the @ replaced by
- * a .
- */
- public static final DnsRecordType RP = new DnsRecordType(0x0011, "RP");
-
- /**
- * AFS database record RFC 1183 Location of database servers of an AFS cell.
- * This record is commonly used by AFS clients to contact AFS cells outside
- * their local domain. A subtype of this record is used by the obsolete
- * DCE/DFS file system.
- */
- public static final DnsRecordType AFSDB = new DnsRecordType(0x0012, "AFSDB");
-
- /**
- * Signature record RFC 2535 Signature record used in SIG(0) (RFC 2931) and
- * TKEY (RFC 2930). RFC 3755 designated RRSIG as the replacement for SIG for
- * use within DNSSEC.
- */
- public static final DnsRecordType SIG = new DnsRecordType(0x0018, "SIG");
-
- /**
- * key record RFC 2535 and RFC 2930 Used only for SIG(0) (RFC 2931) and TKEY
- * (RFC 2930). RFC 3445 eliminated their use for application keys and
- * limited their use to DNSSEC. RFC 3755 designates DNSKEY as the
- * replacement within DNSSEC. RFC 4025 designates IPSECKEY as the
- * replacement for use with IPsec.
- */
- public static final DnsRecordType KEY = new DnsRecordType(0x0019, "KEY");
-
- /**
- * IPv6 address record RFC 3596 Returns a 128-bit IPv6 address, most
- * commonly used to map hostnames to an IP address of the host.
- */
- public static final DnsRecordType AAAA = new DnsRecordType(0x001c, "AAAA");
-
- /**
- * Location record RFC 1876 Specifies a geographical location associated
- * with a domain name.
- */
- public static final DnsRecordType LOC = new DnsRecordType(0x001d, "LOC");
-
- /**
- * Service locator RFC 2782 Generalized service location record, used for
- * newer protocols instead of creating protocol-specific records such as MX.
- */
- public static final DnsRecordType SRV = new DnsRecordType(0x0021, "SRV");
-
- /**
- * Naming Authority Pointer record RFC 3403 Allows regular expression based
- * rewriting of domain names which can then be used as URIs, further domain
- * names to lookups, etc.
- */
- public static final DnsRecordType NAPTR = new DnsRecordType(0x0023, "NAPTR");
-
- /**
- * Key eXchanger record RFC 2230 Used with some cryptographic systems (not
- * including DNSSEC) to identify a key management agent for the associated
- * domain-name. Note that this has nothing to do with DNS Security. It is
- * Informational status, rather than being on the IETF standards-track. It
- * has always had limited deployment, but is still in use.
- */
- public static final DnsRecordType KX = new DnsRecordType(0x0024, "KX");
-
- /**
- * Certificate record RFC 4398 Stores PKIX, SPKI, PGP, etc.
- */
- public static final DnsRecordType CERT = new DnsRecordType(0x0025, "CERT");
-
- /**
- * Delegation name record RFC 2672 DNAME creates an alias for a name and all
- * its subnames, unlike CNAME, which aliases only the exact name in its
- * label. Like the CNAME record, the DNS lookup will continue by retrying
- * the lookup with the new name.
- */
- public static final DnsRecordType DNAME = new DnsRecordType(0x0027, "DNAME");
-
- /**
- * Option record RFC 2671 This is a pseudo DNS record type needed to support
- * EDNS.
- */
- public static final DnsRecordType OPT = new DnsRecordType(0x0029, "OPT");
-
- /**
- * Address Prefix List record RFC 3123 Specify lists of address ranges, e.g.
- * in CIDR format, for various address families. Experimental.
- */
- public static final DnsRecordType APL = new DnsRecordType(0x002a, "APL");
-
- /**
- * Delegation signer record RFC 4034 The record used to identify the DNSSEC
- * signing key of a delegated zone.
- */
- public static final DnsRecordType DS = new DnsRecordType(0x002b, "DS");
-
- /**
- * SSH Public Key Fingerprint record RFC 4255 Resource record for publishing
- * SSH public host key fingerprints in the DNS System, in order to aid in
- * verifying the authenticity of the host. RFC 6594 defines ECC SSH keys and
- * SHA-256 hashes. See the IANA SSHFP RR parameters registry for details.
- */
- public static final DnsRecordType SSHFP = new DnsRecordType(0x002c, "SSHFP");
-
- /**
- * IPsec Key record RFC 4025 Key record that can be used with IPsec.
- */
- public static final DnsRecordType IPSECKEY = new DnsRecordType(0x002d, "IPSECKEY");
-
- /**
- * DNSSEC signature record RFC 4034 Signature for a DNSSEC-secured record
- * set. Uses the same format as the SIG record.
- */
- public static final DnsRecordType RRSIG = new DnsRecordType(0x002e, "RRSIG");
-
- /**
- * Next-Secure record RFC 4034 Part of DNSSEC, used to prove a name does not
- * exist. Uses the same format as the (obsolete) NXT record.
- */
- public static final DnsRecordType NSEC = new DnsRecordType(0x002f, "NSEC");
-
- /**
- * DNS Key record RFC 4034 The key record used in DNSSEC. Uses the same
- * format as the KEY record.
- */
- public static final DnsRecordType DNSKEY = new DnsRecordType(0x0030, "DNSKEY");
-
- /**
- * DHCP identifier record RFC 4701 Used in conjunction with the FQDN option
- * to DHCP.
- */
- public static final DnsRecordType DHCID = new DnsRecordType(0x0031, "DHCID");
-
- /**
- * NSEC record version 3 RFC 5155 An extension to DNSSEC that allows proof
- * of nonexistence for a name without permitting zonewalking.
- */
- public static final DnsRecordType NSEC3 = new DnsRecordType(0x0032, "NSEC3");
-
- /**
- * NSEC3 parameters record RFC 5155 Parameter record for use with NSEC3.
- */
- public static final DnsRecordType NSEC3PARAM = new DnsRecordType(0x0033, "NSEC3PARAM");
-
- /**
- * TLSA certificate association record RFC 6698 A record for DNS-based
- * Authentication of Named Entities (DANE). RFC 6698 defines The TLSA DNS
- * resource record is used to associate a TLS server certificate or public
- * key with the domain name where the record is found, thus forming a 'TLSA
- * certificate association'.
- */
- public static final DnsRecordType TLSA = new DnsRecordType(0x0034, "TLSA");
-
- /**
- * Host Identity Protocol record RFC 5205 Method of separating the end-point
- * identifier and locator roles of IP addresses.
- */
- public static final DnsRecordType HIP = new DnsRecordType(0x0037, "HIP");
-
- /**
- * Sender Policy Framework record RFC 4408 Specified as part of the SPF
- * protocol as an alternative to of storing SPF data in TXT records. Uses
- * the same format as the earlier TXT record.
- */
- public static final DnsRecordType SPF = new DnsRecordType(0x0063, "SPF");
-
- /**
- * Secret key record RFC 2930 A method of providing keying material to be
- * used with TSIG that is encrypted under the public key in an accompanying
- * KEY RR..
- */
- public static final DnsRecordType TKEY = new DnsRecordType(0x00f9, "TKEY");
-
- /**
- * Transaction Signature record RFC 2845 Can be used to authenticate dynamic
- * updates as coming from an approved client, or to authenticate responses
- * as coming from an approved recursive name server similar to DNSSEC.
- */
- public static final DnsRecordType TSIG = new DnsRecordType(0x00fa, "TSIG");
-
- /**
- * Incremental Zone Transfer record RFC 1996 Requests a zone transfer of the
- * given zone but only differences from a previous serial number. This
- * request may be ignored and a full (AXFR) sent in response if the
- * authoritative server is unable to fulfill the request due to
- * configuration or lack of required deltas.
- */
- public static final DnsRecordType IXFR = new DnsRecordType(0x00fb, "IXFR");
-
- /**
- * Authoritative Zone Transfer record RFC 1035 Transfer entire zone file
- * from the master name server to secondary name servers.
- */
- public static final DnsRecordType AXFR = new DnsRecordType(0x00fc, "AXFR");
-
- /**
- * All cached records RFC 1035 Returns all records of all types known to the
- * name server. If the name server does not have any information on the
- * name, the request will be forwarded on. The records returned may not be
- * complete. For example, if there is both an A and an MX for a name, but
- * the name server has only the A record cached, only the A record will be
- * returned. Sometimes referred to as ANY, for example in Windows nslookup
- * and Wireshark.
- */
- public static final DnsRecordType ANY = new DnsRecordType(0x00ff, "ANY");
-
- /**
- * Certification Authority Authorization record RFC 6844 CA pinning,
- * constraining acceptable CAs for a host/domain.
- */
- public static final DnsRecordType CAA = new DnsRecordType(0x0101, "CAA");
-
- /**
- * DNSSEC Trust Authorities record N/A Part of a deployment proposal for
- * DNSSEC without a signed DNS root. See the IANA database and Weiler Spec
- * for details. Uses the same format as the DS record.
- */
- public static final DnsRecordType TA = new DnsRecordType(0x8000, "TA");
-
- /**
- * DNSSEC Lookaside Validation record RFC 4431 For publishing DNSSEC trust
- * anchors outside of the DNS delegation chain. Uses the same format as the
- * DS record. RFC 5074 describes a way of using these records.
- */
- public static final DnsRecordType DLV = new DnsRecordType(0x8001, "DLV");
-
- private static final Map BY_NAME = new HashMap();
- private static final IntObjectHashMap BY_TYPE = new IntObjectHashMap();
- private static final String EXPECTED;
-
- static {
- DnsRecordType[] all = {
- A, NS, CNAME, SOA, PTR, MX, TXT, RP, AFSDB, SIG, KEY, AAAA, LOC, SRV, NAPTR, KX, CERT, DNAME, OPT, APL,
- DS, SSHFP, IPSECKEY, RRSIG, NSEC, DNSKEY, DHCID, NSEC3, NSEC3PARAM, TLSA, HIP, SPF, TKEY, TSIG, IXFR,
- AXFR, ANY, CAA, TA, DLV
- };
-
- final StringBuilder expected = new StringBuilder(512);
-
- expected.append(" (expected: ");
- for (DnsRecordType type: all) {
- BY_NAME.put(type.name(), type);
- BY_TYPE.put(type.intValue(), type);
-
- expected.append(type.name())
- .append('(')
- .append(type.intValue())
- .append("), ");
- }
-
- expected.setLength(expected.length() - 2);
- expected.append(')');
- EXPECTED = expected.toString();
- }
-
- public static DnsRecordType valueOf(int intValue) {
- DnsRecordType result = BY_TYPE.get(intValue);
- if (result == null) {
- return new DnsRecordType(intValue);
- }
- return result;
- }
-
- public static DnsRecordType valueOf(String name) {
- DnsRecordType result = BY_NAME.get(name);
- if (result == null) {
- throw new IllegalArgumentException("name: " + name + EXPECTED);
- }
- return result;
- }
-
- private final int intValue;
- private final String name;
- private String text;
-
- private DnsRecordType(int intValue) {
- this(intValue, "UNKNOWN");
- }
-
- public DnsRecordType(int intValue, String name) {
- if ((intValue & 0xffff) != intValue) {
- throw new IllegalArgumentException("intValue: " + intValue + " (expected: 0 ~ 65535)");
- }
- this.intValue = intValue;
- this.name = name;
- }
-
- /**
- * Returns the name of this type, as seen in bind config files
- */
- public String name() {
- return name;
- }
-
- /**
- * Returns the value of this DnsType as it appears in DNS protocol
- */
- public int intValue() {
- return intValue;
- }
-
- @Override
- public int hashCode() {
- return intValue;
- }
-
- @Override
- public boolean equals(Object o) {
- return o instanceof DnsRecordType && ((DnsRecordType) o).intValue == intValue;
- }
-
- @Override
- public int compareTo(DnsRecordType o) {
- return intValue() - o.intValue();
- }
-
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + intValue() + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java
deleted file mode 100644
index bf85fdee8b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponse.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * A DNS response message.
- */
-public interface DnsResponse extends DnsMessage {
-
- /**
- * Returns {@code true} if responding server is authoritative for the domain
- * name in the query message.
- */
- boolean isAuthoritativeAnswer();
-
- /**
- * Set to {@code true} if responding server is authoritative for the domain
- * name in the query message.
- *
- * @param authoritativeAnswer flag for authoritative answer
- */
- DnsResponse setAuthoritativeAnswer(boolean authoritativeAnswer);
-
- /**
- * Returns {@code true} if response has been truncated, usually if it is
- * over 512 bytes.
- */
- boolean isTruncated();
-
- /**
- * Set to {@code true} if response has been truncated (usually happens for
- * responses over 512 bytes).
- *
- * @param truncated flag for truncation
- */
- DnsResponse setTruncated(boolean truncated);
-
- /**
- * Returns {@code true} if DNS server can handle recursive queries.
- */
- boolean isRecursionAvailable();
-
- /**
- * Set to {@code true} if DNS server can handle recursive queries.
- *
- * @param recursionAvailable flag for recursion availability
- */
- DnsResponse setRecursionAvailable(boolean recursionAvailable);
-
- /**
- * Returns the 4 bit return code.
- */
- DnsResponseCode code();
-
- /**
- * Sets the response code for this message.
- *
- * @param code the response code
- */
- DnsResponse setCode(DnsResponseCode code);
-
- @Override
- DnsResponse setId(int id);
-
- @Override
- DnsResponse setOpCode(DnsOpCode opCode);
-
- @Override
- DnsResponse setRecursionDesired(boolean recursionDesired);
-
- @Override
- DnsResponse setZ(int z);
-
- @Override
- DnsResponse setRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsResponse addRecord(DnsSection section, DnsRecord record);
-
- @Override
- DnsResponse addRecord(DnsSection section, int index, DnsRecord record);
-
- @Override
- DnsResponse clear(DnsSection section);
-
- @Override
- DnsResponse clear();
-
- @Override
- DnsResponse retain();
-
- @Override
- DnsResponse retain(int increment);
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java
deleted file mode 100644
index dcd4c945aa..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseCode.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * The DNS {@code RCODE}, as defined in RFC2929.
- */
-public class DnsResponseCode implements Comparable {
-
- /**
- * The 'NoError' DNS RCODE (0), as defined in RFC1035.
- */
- public static final DnsResponseCode NOERROR = new DnsResponseCode(0, "NoError");
-
- /**
- * The 'FormErr' DNS RCODE (1), as defined in RFC1035.
- */
- public static final DnsResponseCode FORMERR = new DnsResponseCode(1, "FormErr");
-
- /**
- * The 'ServFail' DNS RCODE (2), as defined in RFC1035.
- */
- public static final DnsResponseCode SERVFAIL = new DnsResponseCode(2, "ServFail");
-
- /**
- * The 'NXDomain' DNS RCODE (3), as defined in RFC1035.
- */
- public static final DnsResponseCode NXDOMAIN = new DnsResponseCode(3, "NXDomain");
-
- /**
- * The 'NotImp' DNS RCODE (4), as defined in RFC1035.
- */
- public static final DnsResponseCode NOTIMP = new DnsResponseCode(4, "NotImp");
-
- /**
- * The 'Refused' DNS RCODE (5), as defined in RFC1035.
- */
- public static final DnsResponseCode REFUSED = new DnsResponseCode(5, "Refused");
-
- /**
- * The 'YXDomain' DNS RCODE (6), as defined in RFC2136.
- */
- public static final DnsResponseCode YXDOMAIN = new DnsResponseCode(6, "YXDomain");
-
- /**
- * The 'YXRRSet' DNS RCODE (7), as defined in RFC2136.
- */
- public static final DnsResponseCode YXRRSET = new DnsResponseCode(7, "YXRRSet");
-
- /**
- * The 'NXRRSet' DNS RCODE (8), as defined in RFC2136.
- */
- public static final DnsResponseCode NXRRSET = new DnsResponseCode(8, "NXRRSet");
-
- /**
- * The 'NotAuth' DNS RCODE (9), as defined in RFC2136.
- */
- public static final DnsResponseCode NOTAUTH = new DnsResponseCode(9, "NotAuth");
-
- /**
- * The 'NotZone' DNS RCODE (10), as defined in RFC2136.
- */
- public static final DnsResponseCode NOTZONE = new DnsResponseCode(10, "NotZone");
-
- /**
- * The 'BADVERS' or 'BADSIG' DNS RCODE (16), as defined in RFC2671
- * and RFC2845.
- */
- public static final DnsResponseCode BADVERS_OR_BADSIG = new DnsResponseCode(16, "BADVERS_OR_BADSIG");
-
- /**
- * The 'BADKEY' DNS RCODE (17), as defined in RFC2845.
- */
- public static final DnsResponseCode BADKEY = new DnsResponseCode(17, "BADKEY");
-
- /**
- * The 'BADTIME' DNS RCODE (18), as defined in RFC2845.
- */
- public static final DnsResponseCode BADTIME = new DnsResponseCode(18, "BADTIME");
-
- /**
- * The 'BADMODE' DNS RCODE (19), as defined in RFC2930.
- */
- public static final DnsResponseCode BADMODE = new DnsResponseCode(19, "BADMODE");
-
- /**
- * The 'BADNAME' DNS RCODE (20), as defined in RFC2930.
- */
- public static final DnsResponseCode BADNAME = new DnsResponseCode(20, "BADNAME");
-
- /**
- * The 'BADALG' DNS RCODE (21), as defined in RFC2930.
- */
- public static final DnsResponseCode BADALG = new DnsResponseCode(21, "BADALG");
-
- /**
- * Returns the {@link DnsResponseCode} that corresponds with the given {@code responseCode}.
- *
- * @param responseCode the DNS RCODE
- *
- * @return the corresponding {@link DnsResponseCode}
- */
- public static DnsResponseCode valueOf(int responseCode) {
- switch (responseCode) {
- case 0:
- return NOERROR;
- case 1:
- return FORMERR;
- case 2:
- return SERVFAIL;
- case 3:
- return NXDOMAIN;
- case 4:
- return NOTIMP;
- case 5:
- return REFUSED;
- case 6:
- return YXDOMAIN;
- case 7:
- return YXRRSET;
- case 8:
- return NXRRSET;
- case 9:
- return NOTAUTH;
- case 10:
- return NOTZONE;
- case 16:
- return BADVERS_OR_BADSIG;
- case 17:
- return BADKEY;
- case 18:
- return BADTIME;
- case 19:
- return BADMODE;
- case 20:
- return BADNAME;
- case 21:
- return BADALG;
- default:
- return new DnsResponseCode(responseCode);
- }
- }
-
- private final int code;
- private final String name;
- private String text;
-
- private DnsResponseCode(int code) {
- this(code, "UNKNOWN");
- }
-
- public DnsResponseCode(int code, String name) {
- if (code < 0 || code > 65535) {
- throw new IllegalArgumentException("code: " + code + " (expected: 0 ~ 65535)");
- }
-
- this.code = code;
- this.name = checkNotNull(name, "name");
- }
-
- /**
- * Returns the error code for this {@link DnsResponseCode}.
- */
- public int intValue() {
- return code;
- }
-
- @Override
- public int compareTo(DnsResponseCode o) {
- return intValue() - o.intValue();
- }
-
- @Override
- public int hashCode() {
- return intValue();
- }
-
- /**
- * Equality of {@link DnsResponseCode} only depends on {@link #intValue()}.
- */
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof DnsResponseCode)) {
- return false;
- }
-
- return intValue() == ((DnsResponseCode) o).intValue();
- }
-
- /**
- * Returns a formatted error message for this {@link DnsResponseCode}.
- */
- @Override
- public String toString() {
- String text = this.text;
- if (text == null) {
- this.text = text = name + '(' + intValue() + ')';
- }
- return text;
- }
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java
deleted file mode 100644
index 1d0c842d1b..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/DnsSection.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-/**
- * Represents a section of a {@link DnsMessage}.
- */
-public enum DnsSection {
- /**
- * The section that contains {@link DnsQuestion}s.
- */
- QUESTION,
- /**
- * The section that contains the answer {@link DnsRecord}s.
- */
- ANSWER,
- /**
- * The section that contains the authority {@link DnsRecord}s.
- */
- AUTHORITY,
- /**
- * The section that contains the additional {@link DnsRecord}s.
- */
- ADDITIONAL
-}
diff --git a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java b/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java
deleted file mode 100644
index e45c7dfcac..0000000000
--- a/netty-bp/codec-dns/src/main/java/io/netty/handler/codec/dns/package-info.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-/**
- * DNS codec.
- */
-package io.netty.handler.codec.dns;
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java
deleted file mode 100644
index d55a0b1354..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/AbstractDnsRecordTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class AbstractDnsRecordTest {
-
- @Test
- public void testValidDomainName() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals(name + '.', record.name());
- }
-
- @Test
- public void testValidDomainNameUmlaut() {
- String name = "ä";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals("xn--4ca.", record.name());
- }
-
- @Test
- public void testValidDomainNameTrailingDot() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals(name, record.name());
- }
-
- @Test
- public void testValidDomainNameUmlautTrailingDot() {
- String name = "ä.";
- AbstractDnsRecord record = new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- Assert.assertEquals("xn--4ca.", record.name());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testValidDomainNameLength() {
- String name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testValidDomainNameUmlautLength() {
- String name = "äaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- new AbstractDnsRecord(name, DnsRecordType.A, 0) { };
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java
deleted file mode 100644
index 244422fcdb..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoderTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class DefaultDnsRecordDecoderTest {
-
- @Test
- public void testDecodeName() {
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0
- }));
- }
-
- @Test
- public void testDecodeNameWithoutTerminator() {
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o'
- }));
- }
-
- @Test
- public void testDecodeNameWithExtraTerminator() {
- // Should not be decoded as 'netty.io..'
- testDecodeName("netty.io.", Unpooled.wrappedBuffer(new byte[] {
- 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0, 0
- }));
- }
-
- @Test
- public void testDecodeEmptyName() {
- testDecodeName(".", Unpooled.buffer().writeByte(0));
- }
-
- @Test
- public void testDecodeEmptyNameFromEmptyBuffer() {
- testDecodeName(".", Unpooled.EMPTY_BUFFER);
- }
-
- @Test
- public void testDecodeEmptyNameFromExtraZeroes() {
- testDecodeName(".", Unpooled.wrappedBuffer(new byte[] { 0, 0 }));
- }
-
- private static void testDecodeName(String expected, ByteBuf buffer) {
- try {
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- assertEquals(expected, decoder.decodeName0(buffer));
- } finally {
- buffer.release();
- }
- }
-
- @Test
- public void testDecodePtrRecord() throws Exception {
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- ByteBuf buffer = Unpooled.buffer().writeByte(0);
- int readerIndex = buffer.readerIndex();
- int writerIndex = buffer.writerIndex();
- try {
- DnsPtrRecord record = (DnsPtrRecord) decoder.decodeRecord(
- "netty.io", DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 0, 1);
- assertEquals("netty.io.", record.name());
- assertEquals(DnsRecord.CLASS_IN, record.dnsClass());
- assertEquals(60, record.timeToLive());
- assertEquals(DnsRecordType.PTR, record.type());
- assertEquals(readerIndex, buffer.readerIndex());
- assertEquals(writerIndex, buffer.writerIndex());
- } finally {
- buffer.release();
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java
deleted file mode 100644
index ac8b5b65eb..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DefaultDnsRecordEncoderTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.util.internal.StringUtil;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class DefaultDnsRecordEncoderTest {
-
- @Test
- public void testEncodeName() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io.");
- }
-
- @Test
- public void testEncodeNameWithoutTerminator() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io");
- }
-
- @Test
- public void testEncodeNameWithExtraTerminator() throws Exception {
- testEncodeName(new byte[] { 5, 'n', 'e', 't', 't', 'y', 2, 'i', 'o', 0 }, "netty.io..");
- }
-
- // Test for https://github.com/netty/netty/issues/5014
- @Test
- public void testEncodeEmptyName() throws Exception {
- testEncodeName(new byte[] { 0 }, StringUtil.EMPTY_STRING);
- }
-
- @Test
- public void testEncodeRootName() throws Exception {
- testEncodeName(new byte[] { 0 }, ".");
- }
-
- private static void testEncodeName(byte[] expected, String name) throws Exception {
- DefaultDnsRecordEncoder encoder = new DefaultDnsRecordEncoder();
- ByteBuf out = Unpooled.buffer();
- ByteBuf expectedBuf = Unpooled.wrappedBuffer(expected);
- try {
- encoder.encodeName(name, out);
- assertEquals(expectedBuf, out);
- } finally {
- out.release();
- expectedBuf.release();
- }
- }
-
- @Test
- public void testDecodeMessageCompression() throws Exception {
- // See https://www.ietf.org/rfc/rfc1035 [4.1.4. Message compression]
- DefaultDnsRecordDecoder decoder = new DefaultDnsRecordDecoder();
- byte[] rfcExample = new byte[] { 1, 'F', 3, 'I', 'S', 'I', 4, 'A', 'R', 'P', 'A',
- 0, 3, 'F', 'O', 'O',
- (byte) 0xC0, 0, // this is 20 in the example
- (byte) 0xC0, 6, // this is 26 in the example
- };
- DefaultDnsRawRecord rawPlainRecord = null;
- DefaultDnsRawRecord rawUncompressedRecord = null;
- DefaultDnsRawRecord rawUncompressedIndexedRecord = null;
- ByteBuf buffer = Unpooled.wrappedBuffer(rfcExample);
- try {
- // First lets test that our utility funciton can correctly handle index references and decompression.
- String plainName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate());
- assertEquals("F.ISI.ARPA.", plainName);
- String uncompressedPlainName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate().setIndex(16, 20));
- assertEquals(plainName, uncompressedPlainName);
- String uncompressedIndexedName = DefaultDnsRecordDecoder.decodeName(buffer.duplicate().setIndex(12, 20));
- assertEquals("FOO." + plainName, uncompressedIndexedName);
-
- // Now lets make sure out object parsing produces the same results for non PTR type (just use CNAME).
- rawPlainRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- plainName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 0, 11);
- assertEquals(plainName, rawPlainRecord.name());
- assertEquals(plainName, DefaultDnsRecordDecoder.decodeName(rawPlainRecord.content()));
-
- rawUncompressedRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- uncompressedPlainName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 16, 4);
- assertEquals(uncompressedPlainName, rawUncompressedRecord.name());
- assertEquals(uncompressedPlainName, DefaultDnsRecordDecoder.decodeName(rawUncompressedRecord.content()));
-
- rawUncompressedIndexedRecord = (DefaultDnsRawRecord) decoder.decodeRecord(
- uncompressedIndexedName, DnsRecordType.CNAME, DnsRecord.CLASS_IN, 60, buffer, 12, 8);
- assertEquals(uncompressedIndexedName, rawUncompressedIndexedRecord.name());
- assertEquals(uncompressedIndexedName,
- DefaultDnsRecordDecoder.decodeName(rawUncompressedIndexedRecord.content()));
-
- // Now lets make sure out object parsing produces the same results for PTR type.
- DnsPtrRecord ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- plainName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 0, 11);
- assertEquals(plainName, ptrRecord.name());
- assertEquals(plainName, ptrRecord.hostname());
-
- ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- uncompressedPlainName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 16, 4);
- assertEquals(uncompressedPlainName, ptrRecord.name());
- assertEquals(uncompressedPlainName, ptrRecord.hostname());
-
- ptrRecord = (DnsPtrRecord) decoder.decodeRecord(
- uncompressedIndexedName, DnsRecordType.PTR, DnsRecord.CLASS_IN, 60, buffer, 12, 8);
- assertEquals(uncompressedIndexedName, ptrRecord.name());
- assertEquals(uncompressedIndexedName, ptrRecord.hostname());
- } finally {
- if (rawPlainRecord != null) {
- rawPlainRecord.release();
- }
- if (rawUncompressedRecord != null) {
- rawUncompressedRecord.release();
- }
- if (rawUncompressedIndexedRecord != null) {
- rawUncompressedIndexedRecord.release();
- }
- buffer.release();
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java
deleted file mode 100644
index 48cb948f45..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsQueryTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.channel.embedded.EmbeddedChannel;
-
-import io.netty.channel.socket.DatagramPacket;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
-public class DnsQueryTest {
-
- @Test
- public void writeQueryTest() throws Exception {
- InetSocketAddress addr = new InetSocketAddress("8.8.8.8", 53);
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsQueryEncoder());
- List queries = new ArrayList(5);
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("1.0.0.127.in-addr.arpa", DnsRecordType.PTR)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("www.example.com", DnsRecordType.A)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.AAAA)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.MX)));
- queries.add(new DatagramDnsQuery(null, addr, 1).setRecord(
- DnsSection.QUESTION,
- new DefaultDnsQuestion("example.com", DnsRecordType.CNAME)));
-
- for (DnsQuery query: queries) {
- assertThat(query.count(DnsSection.QUESTION), is(1));
- assertThat(query.count(DnsSection.ANSWER), is(0));
- assertThat(query.count(DnsSection.AUTHORITY), is(0));
- assertThat(query.count(DnsSection.ADDITIONAL), is(0));
-
- embedder.writeOutbound(query);
-
- DatagramPacket packet = (DatagramPacket) embedder.readOutbound();
- Assert.assertTrue(packet.content().isReadable());
- packet.release();
- Assert.assertNull(embedder.readOutbound());
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java
deleted file mode 100644
index aeeab95b04..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsRecordTypeTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import org.junit.Test;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
-public class DnsRecordTypeTest {
-
- private static List allTypes() throws Exception {
- List result = new ArrayList();
- for (Field field : DnsRecordType.class.getFields()) {
- if ((field.getModifiers() & Modifier.STATIC) != 0 && field.getType() == DnsRecordType.class) {
- result.add((DnsRecordType) field.get(null));
- }
- }
- assertFalse(result.isEmpty());
- return result;
- }
-
- @Test
- public void testSanity() throws Exception {
- assertEquals("More than one type has the same int value",
- allTypes().size(), new HashSet(allTypes()).size());
- }
-
- /**
- * Test of hashCode method, of class DnsRecordType.
- */
- @Test
- public void testHashCode() throws Exception {
- for (DnsRecordType t : allTypes()) {
- assertEquals(t.intValue(), t.hashCode());
- }
- }
-
- /**
- * Test of equals method, of class DnsRecordType.
- */
- @Test
- public void testEquals() throws Exception {
- for (DnsRecordType t1 : allTypes()) {
- for (DnsRecordType t2 : allTypes()) {
- if (t1 != t2) {
- assertNotEquals(t1, t2);
- }
- }
- }
- }
-
- /**
- * Test of find method, of class DnsRecordType.
- */
- @Test
- public void testFind() throws Exception {
- for (DnsRecordType t : allTypes()) {
- DnsRecordType found = DnsRecordType.valueOf(t.intValue());
- assertSame(t, found);
- found = DnsRecordType.valueOf(t.name());
- assertSame(t.name(), t, found);
- }
- }
-}
diff --git a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java b/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
deleted file mode 100644
index e0d1ec1a3f..0000000000
--- a/netty-bp/codec-dns/src/test/java/io/netty/handler/codec/dns/DnsResponseTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2013 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.handler.codec.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.embedded.EmbeddedChannel;
-import io.netty.channel.socket.DatagramPacket;
-import io.netty.handler.codec.CorruptedFrameException;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-import java.net.InetSocketAddress;
-
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
-
-public class DnsResponseTest {
-
- private static final byte[][] packets = {
- {
- 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 1, 0, 1, -64, 12, 0, 1, 0, 1, 0, 0, 16, -113, 0, 4, -64, 0, 43, 10
- },
- {
- 0, 1, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 28, 0, 1, -64, 12, 0, 28, 0, 1, 0, 0, 69, -8, 0, 16, 32, 1, 5, 0, 0, -120, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 16
- },
- {
- 0, 2, -127, -128, 0, 1, 0, 0, 0, 1, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 15, 0, 1, -64, 16, 0, 6, 0, 1, 0, 0, 3, -43, 0, 45, 3, 115, 110, 115, 3, 100,
- 110, 115, 5, 105, 99, 97, 110, 110, 3, 111, 114, 103, 0, 3, 110, 111, 99, -64, 49, 119, -4, 39,
- 112, 0, 0, 28, 32, 0, 0, 14, 16, 0, 18, 117, 0, 0, 0, 14, 16
- },
- {
- 0, 3, -127, -128, 0, 1, 0, 1, 0, 0, 0, 0, 3, 119, 119, 119, 7, 101, 120, 97, 109, 112, 108, 101, 3,
- 99, 111, 109, 0, 0, 16, 0, 1, -64, 12, 0, 16, 0, 1, 0, 0, 84, 75, 0, 12, 11, 118, 61, 115, 112,
- 102, 49, 32, 45, 97, 108, 108
- },
- {
- -105, 19, -127, 0, 0, 1, 0, 0, 0, 13, 0, 0, 2, 104, 112, 11, 116, 105, 109, 98, 111, 117, 100, 114,
- 101, 97, 117, 3, 111, 114, 103, 0, 0, 1, 0, 1, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 20, 1, 68, 12, 82,
- 79, 79, 84, 45, 83, 69, 82, 86, 69, 82, 83, 3, 78, 69, 84, 0, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1,
- 70, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 69, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4,
- 1, 75, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 67, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0,
- 4, 1, 76, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 71, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0,
- 0, 4, 1, 73, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 66, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23,
- 0, 0, 4, 1, 77, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 65, -64, 49, 0, 0, 2, 0, 1, 0, 7,
- -23, 0, 0, 4, 1, 72, -64, 49, 0, 0, 2, 0, 1, 0, 7, -23, 0, 0, 4, 1, 74, -64, 49
- }
- };
-
- private static final byte[] malformedLoopPacket = {
- 0, 4, -127, -128, 0, 1, 0, 0, 0, 0, 0, 0, -64, 12, 0, 1, 0, 1
- };
-
- @Test
- public void readResponseTest() throws Exception {
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
- for (byte[] p: packets) {
- ByteBuf packet = embedder.alloc().buffer(512).writeBytes(p);
- embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
- AddressedEnvelope envelope = (AddressedEnvelope) embedder.readInbound();
- assertThat(envelope, is(instanceOf(DatagramDnsResponse.class)));
- DnsResponse response = envelope.content();
- assertThat(response, is(sameInstance((Object) envelope)));
-
- ByteBuf raw = Unpooled.wrappedBuffer(p);
- assertThat(response.id(), is(raw.getUnsignedShort(0)));
- assertThat(response.count(DnsSection.QUESTION), is(raw.getUnsignedShort(4)));
- assertThat(response.count(DnsSection.ANSWER), is(raw.getUnsignedShort(6)));
- assertThat(response.count(DnsSection.AUTHORITY), is(raw.getUnsignedShort(8)));
- assertThat(response.count(DnsSection.ADDITIONAL), is(raw.getUnsignedShort(10)));
-
- envelope.release();
- }
- }
-
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
- @Test
- public void readMalormedResponseTest() throws Exception {
- EmbeddedChannel embedder = new EmbeddedChannel(new DatagramDnsResponseDecoder());
- ByteBuf packet = embedder.alloc().buffer(512).writeBytes(malformedLoopPacket);
- exception.expect(CorruptedFrameException.class);
- embedder.writeInbound(new DatagramPacket(packet, null, new InetSocketAddress(0)));
- }
-}
diff --git a/netty-bp/pom.xml b/netty-bp/pom.xml
deleted file mode 100644
index 660bf5d912..0000000000
--- a/netty-bp/pom.xml
+++ /dev/null
@@ -1,52 +0,0 @@
-
-
- org.asynchttpclient
- async-http-client-project
- 2.0.25-SNAPSHOT
-
- 4.0.0
- netty-bp
- Asynchronous Http Client Extras Parent
- pom
-
- The Async Http Client Netty Backport parent.
-
-
-
- codec-dns
- resolver
- resolver-dns
-
-
-
-
- org.apache.directory.server
- apacheds-protocol-dns
- 1.5.7
- test
-
-
- junit
- junit
- 4.12
- test
-
-
- org.hamcrest
- hamcrest-library
- 1.3
- test
-
-
-
-
-
-
- maven-javadoc-plugin
-
- -Xdoclint:none
-
-
-
-
-
diff --git a/netty-bp/resolver-dns/pom.xml b/netty-bp/resolver-dns/pom.xml
deleted file mode 100644
index e2d839865d..0000000000
--- a/netty-bp/resolver-dns/pom.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
- 4.0.0
-
- org.asynchttpclient
- netty-bp
- 2.0.25-SNAPSHOT
-
-
- netty-resolver-dns
-
- Netty/Resolver/DNS
-
-
-
- ${project.groupId}
- netty-resolver
- ${project.version}
-
-
- ${project.groupId}
- netty-codec-dns
- ${project.version}
-
-
- io.netty
- netty-transport
-
-
-
-
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java b/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java
deleted file mode 100644
index 18c0ab762c..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/channel/ReflectiveChannelFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.channel;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.util.internal.StringUtil;
-
-/**
- * A {@link ChannelFactory} that instantiates a new {@link Channel} by invoking its default constructor reflectively.
- */
-public class ReflectiveChannelFactory implements ChannelFactory {
-
- private final Class extends T> clazz;
-
- public ReflectiveChannelFactory(Class extends T> clazz) {
- if (clazz == null) {
- throw new NullPointerException("clazz");
- }
- this.clazz = clazz;
- }
-
- @Override
- public T newChannel() {
- try {
- return clazz.newInstance();
- } catch (Throwable t) {
- throw new ChannelException("Unable to create Channel from class " + clazz, t);
- }
- }
-
- @Override
- public String toString() {
- return StringUtil.simpleClassName(clazz) + ".class";
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java
deleted file mode 100644
index 9a28e2ef7e..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsCache.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import io.netty.channel.EventLoop;
-import io.netty.util.internal.PlatformDependent;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.TimeUnit;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-import static io.netty.util.internal.ObjectUtil2.checkPositiveOrZero;
-
-/**
- * Default implementation of {@link DnsCache}, backed by a {@link ConcurrentMap}.
- */
-public class DefaultDnsCache implements DnsCache {
-
- private final ConcurrentMap> resolveCache = PlatformDependent.newConcurrentHashMap();
- private final int minTtl;
- private final int maxTtl;
- private final int negativeTtl;
-
- /**
- * Create a cache that respects the TTL returned by the DNS server
- * and doesn't cache negative responses.
- */
- public DefaultDnsCache() {
- this(0, Integer.MAX_VALUE, 0);
- }
-
- /**
- * Create a cache.
- * @param minTtl the minimum TTL
- * @param maxTtl the maximum TTL
- * @param negativeTtl the TTL for failed queries
- */
- public DefaultDnsCache(int minTtl, int maxTtl, int negativeTtl) {
- this.minTtl = checkPositiveOrZero(minTtl, "minTtl");
- this.maxTtl = checkPositiveOrZero(maxTtl, "maxTtl");
- if (minTtl > maxTtl) {
- throw new IllegalArgumentException(
- "minTtl: " + minTtl + ", maxTtl: " + maxTtl + " (expected: 0 <= minTtl <= maxTtl)");
- }
- this.negativeTtl = checkPositiveOrZero(negativeTtl, "negativeTtl");
- }
-
- /**
- * Returns the minimum TTL of the cached DNS resource records (in seconds).
- *
- * @see #maxTtl()
- */
- public int minTtl() {
- return minTtl;
- }
-
- /**
- * Returns the maximum TTL of the cached DNS resource records (in seconds).
- *
- * @see #minTtl()
- */
- public int maxTtl() {
- return maxTtl;
- }
-
- /**
- * Returns the TTL of the cache for the failed DNS queries (in seconds). The default value is {@code 0}, which
- * disables the cache for negative results.
- */
- public int negativeTtl() {
- return negativeTtl;
- }
-
- @Override
- public void clear() {
- for (Iterator>> i = resolveCache.entrySet().iterator(); i.hasNext();) {
- final Map.Entry> e = i.next();
- i.remove();
- cancelExpiration(e.getValue());
- }
- }
-
- @Override
- public boolean clear(String hostname) {
- checkNotNull(hostname, "hostname");
- boolean removed = false;
- for (Iterator>> i = resolveCache.entrySet().iterator(); i.hasNext();) {
- final Map.Entry> e = i.next();
- if (e.getKey().equals(hostname)) {
- i.remove();
- cancelExpiration(e.getValue());
- removed = true;
- }
- }
- return removed;
- }
-
- @Override
- public List get(String hostname) {
- checkNotNull(hostname, "hostname");
- return resolveCache.get(hostname);
- }
-
- private List cachedEntries(String hostname) {
- List oldEntries = resolveCache.get(hostname);
- final List entries;
- if (oldEntries == null) {
- List newEntries = new ArrayList(8);
- oldEntries = resolveCache.putIfAbsent(hostname, newEntries);
- entries = oldEntries != null? oldEntries : newEntries;
- } else {
- entries = oldEntries;
- }
- return entries;
- }
-
- @Override
- public void cache(String hostname, InetAddress address, long originalTtl, EventLoop loop) {
- if (maxTtl == 0) {
- return;
- }
- checkNotNull(hostname, "hostname");
- checkNotNull(address, "address");
- checkNotNull(loop, "loop");
-
- final int ttl = Math.max(minTtl, (int) Math.min(maxTtl, originalTtl));
- final List entries = cachedEntries(hostname);
- final DnsCacheEntry e = new DnsCacheEntry(hostname, address);
-
- synchronized (entries) {
- if (!entries.isEmpty()) {
- final DnsCacheEntry firstEntry = entries.get(0);
- if (firstEntry.cause() != null) {
- assert entries.size() == 1;
- firstEntry.cancelExpiration();
- entries.clear();
- }
- }
- entries.add(e);
- }
-
- scheduleCacheExpiration(entries, e, ttl, loop);
- }
-
- @Override
- public void cache(String hostname, Throwable cause, EventLoop loop) {
- if (negativeTtl == 0) {
- return;
- }
- checkNotNull(hostname, "hostname");
- checkNotNull(cause, "cause");
- checkNotNull(loop, "loop");
-
- final List entries = cachedEntries(hostname);
- final DnsCacheEntry e = new DnsCacheEntry(hostname, cause);
-
- synchronized (entries) {
- final int numEntries = entries.size();
- for (int i = 0; i < numEntries; i ++) {
- entries.get(i).cancelExpiration();
- }
- entries.clear();
- entries.add(e);
- }
-
- scheduleCacheExpiration(entries, e, negativeTtl, loop);
- }
-
- private static void cancelExpiration(List entries) {
- final int numEntries = entries.size();
- for (int i = 0; i < numEntries; i++) {
- entries.get(i).cancelExpiration();
- }
- }
-
- private void scheduleCacheExpiration(final List entries,
- final DnsCacheEntry e,
- int ttl,
- EventLoop loop) {
- e.scheduleExpiration(loop, new Runnable() {
- @Override
- public void run() {
- synchronized (entries) {
- entries.remove(e);
- if (entries.isEmpty()) {
- resolveCache.remove(e.hostname());
- }
- }
- }
- }, ttl, TimeUnit.SECONDS);
- }
-
- @Override
- public String toString() {
- return new StringBuilder()
- .append("DefaultDnsCache(minTtl=")
- .append(minTtl).append(", maxTtl=")
- .append(maxTtl).append(", negativeTtl=")
- .append(negativeTtl).append(", cached resolved hostname=")
- .append(resolveCache.size()).append(")")
- .toString();
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java
deleted file mode 100644
index 0efd244915..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddresses.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import java.net.InetSocketAddress;
-
-abstract class DefaultDnsServerAddresses extends DnsServerAddresses {
-
- protected final InetSocketAddress[] addresses;
- private final String strVal;
-
- DefaultDnsServerAddresses(String type, InetSocketAddress[] addresses) {
- this.addresses = addresses;
-
- final StringBuilder buf = new StringBuilder(type.length() + 2 + addresses.length * 16);
- buf.append(type).append('(');
-
- for (InetSocketAddress a: addresses) {
- buf.append(a).append(", ");
- }
-
- buf.setLength(buf.length() - 2);
- buf.append(')');
-
- strVal = buf.toString();
- }
-
- @Override
- public String toString() {
- return strVal;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java
deleted file mode 100644
index 24a45b5f2e..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsAddressResolverGroup.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.EventLoop;
-import io.netty.channel.ReflectiveChannelFactory;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.resolver.AddressResolver;
-import io.netty.resolver.AddressResolverGroup;
-import io.netty.resolver.InetSocketAddressResolver;
-import io.netty.resolver.NameResolver;
-import io.netty.util.concurrent.EventExecutor;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.StringUtil;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.List;
-import java.util.concurrent.ConcurrentMap;
-
-import static io.netty.util.internal.PlatformDependent.newConcurrentHashMap;
-
-/**
- * A {@link AddressResolverGroup} of {@link DnsNameResolver}s.
- */
-public class DnsAddressResolverGroup extends AddressResolverGroup {
-
- private final ChannelFactory extends DatagramChannel> channelFactory;
- private final DnsServerAddresses nameServerAddresses;
-
- private final ConcurrentMap> resolvesInProgress = newConcurrentHashMap();
- private final ConcurrentMap>> resolveAllsInProgress = newConcurrentHashMap();
-
- public DnsAddressResolverGroup(
- Class extends DatagramChannel> channelType,
- DnsServerAddresses nameServerAddresses) {
- this(new ReflectiveChannelFactory(channelType), nameServerAddresses);
- }
-
- public DnsAddressResolverGroup(
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) {
- this.channelFactory = channelFactory;
- this.nameServerAddresses = nameServerAddresses;
- }
-
- @SuppressWarnings("deprecation")
- @Override
- protected final AddressResolver newResolver(EventExecutor executor) throws Exception {
- if (!(executor instanceof EventLoop)) {
- throw new IllegalStateException(
- "unsupported executor type: " + StringUtil.simpleClassName(executor) +
- " (expected: " + StringUtil.simpleClassName(EventLoop.class));
- }
-
- return newResolver((EventLoop) executor, channelFactory, nameServerAddresses);
- }
-
- /**
- * @deprecated Override {@link #newNameResolver(EventLoop, ChannelFactory, DnsServerAddresses)}.
- */
- @Deprecated
- protected AddressResolver newResolver(
- EventLoop eventLoop, ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) throws Exception {
-
- final NameResolver resolver = new InflightNameResolver(
- eventLoop,
- newNameResolver(eventLoop, channelFactory, nameServerAddresses),
- resolvesInProgress,
- resolveAllsInProgress);
-
- return new InetSocketAddressResolver(eventLoop, resolver);
- }
-
- /**
- * Creates a new {@link NameResolver}. Override this method to create an alternative {@link NameResolver}
- * implementation or override the default configuration.
- */
- protected NameResolver newNameResolver(EventLoop eventLoop,
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses) throws Exception {
- return new DnsNameResolverBuilder(eventLoop)
- .channelFactory(channelFactory)
- .nameServerAddresses(nameServerAddresses)
- .build();
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java
deleted file mode 100644
index 79ea3876d5..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCache.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright 2016 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import io.netty.channel.EventLoop;
-
-import java.net.InetAddress;
-import java.util.List;
-
-/**
- * A cache for DNS resolution entries.
- */
-public interface DnsCache {
-
- /**
- * Clears all the resolved addresses cached by this resolver.
- *
- * @see #clear(String)
- */
- void clear();
-
- /**
- * Clears the resolved addresses of the specified host name from the cache of this resolver.
- *
- * @return {@code true} if and only if there was an entry for the specified host name in the cache and
- * it has been removed by this method
- */
- boolean clear(String hostname);
-
- /**
- * Return the cached entries for the given hostname.
- * @param hostname the hostname
- * @return the cached entries
- */
- List get(String hostname);
-
- /**
- * Cache a resolved address for a given hostname.
- * @param hostname the hostname
- * @param address the resolved adresse
- * @param originalTtl the TLL as returned by the DNS server
- * @param loop the {@link EventLoop} used to register the TTL timeout
- */
- void cache(String hostname, InetAddress address, long originalTtl, EventLoop loop);
-
- /**
- * Cache the resolution failure for a given hostname.
- * @param hostname the hostname
- * @param cause the resolution failure
- * @param loop the {@link EventLoop} used to register the TTL timeout
- */
- void cache(String hostname, Throwable cause, EventLoop loop);
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java
deleted file mode 100644
index 789ef7ab84..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsCacheEntry.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-import io.netty.channel.EventLoop;
-import io.netty.util.concurrent.ScheduledFuture;
-
-import java.net.InetAddress;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Entry in {@link DnsCache}.
- */
-public final class DnsCacheEntry {
-
- private final String hostname;
- private final InetAddress address;
- private final Throwable cause;
- private volatile ScheduledFuture> expirationFuture;
-
- public DnsCacheEntry(String hostname, InetAddress address) {
- this.hostname = checkNotNull(hostname, "hostname");
- this.address = checkNotNull(address, "address");
- cause = null;
- }
-
- public DnsCacheEntry(String hostname, Throwable cause) {
- this.hostname = checkNotNull(hostname, "hostname");
- this.cause = checkNotNull(cause, "cause");
- address = null;
- }
-
- public String hostname() {
- return hostname;
- }
-
- public InetAddress address() {
- return address;
- }
-
- public Throwable cause() {
- return cause;
- }
-
- void scheduleExpiration(EventLoop loop, Runnable task, long delay, TimeUnit unit) {
- assert expirationFuture == null: "expiration task scheduled already";
- expirationFuture = loop.schedule(task, delay, unit);
- }
-
- void cancelExpiration() {
- ScheduledFuture> expirationFuture = this.expirationFuture;
- if (expirationFuture != null) {
- expirationFuture.cancel(false);
- }
- }
-
- @Override
- public String toString() {
- if (cause != null) {
- return hostname + '/' + cause;
- } else {
- return address.toString();
- }
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
deleted file mode 100644
index 27520555ae..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
+++ /dev/null
@@ -1,709 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoop;
-import io.netty.channel.FixedRecvByteBufAllocator;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.handler.codec.dns.DatagramDnsQueryEncoder;
-import io.netty.handler.codec.dns.DatagramDnsResponse;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DatagramDnsResponseDecoder;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.resolver.HostsFileEntriesResolver;
-import io.netty.resolver.InetNameResolver;
-import io.netty.util.NetUtil;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.concurrent.FastThreadLocal;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.PlatformDependent;
-import io.netty.util.internal.StringUtil2;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.net.IDN;
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil2.*;
-
-/**
- * A DNS-based {@link InetNameResolver}.
- */
-public class DnsNameResolver extends InetNameResolver {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsNameResolver.class);
- private static final String LOCALHOST = "localhost";
- private static final InetAddress LOCALHOST_ADDRESS;
-
- static final InternetProtocolFamily[] DEFAULT_RESOLVE_ADDRESS_TYPES = new InternetProtocolFamily[2];
- static final String[] DEFAULT_SEACH_DOMAINS;
-
- static {
- // Note that we did not use SystemPropertyUtil.getBoolean() here to emulate the behavior of JDK.
- if (Boolean.getBoolean("java.net.preferIPv6Addresses")) {
- DEFAULT_RESOLVE_ADDRESS_TYPES[0] = InternetProtocolFamily.IPv6;
- DEFAULT_RESOLVE_ADDRESS_TYPES[1] = InternetProtocolFamily.IPv4;
- LOCALHOST_ADDRESS = NetUtil.LOCALHOST6;
- logger.debug("-Djava.net.preferIPv6Addresses: true");
- } else {
- DEFAULT_RESOLVE_ADDRESS_TYPES[0] = InternetProtocolFamily.IPv4;
- DEFAULT_RESOLVE_ADDRESS_TYPES[1] = InternetProtocolFamily.IPv6;
- LOCALHOST_ADDRESS = NetUtil.LOCALHOST4;
- logger.debug("-Djava.net.preferIPv6Addresses: false");
- }
- }
-
- static {
- String[] searchDomains;
- try {
- Class> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
- Method open = configClass.getMethod("open");
- Method nameservers = configClass.getMethod("searchlist");
- Object instance = open.invoke(null);
-
- @SuppressWarnings("unchecked")
- List list = (List) nameservers.invoke(instance);
- searchDomains = list.toArray(new String[list.size()]);
- } catch (Exception ignore) {
- // Failed to get the system name search domain list.
- searchDomains = EmptyArrays.EMPTY_STRINGS;
- }
- DEFAULT_SEACH_DOMAINS = searchDomains;
- }
-
- private static final DatagramDnsResponseDecoder DECODER = new DatagramDnsResponseDecoder();
- private static final DatagramDnsQueryEncoder ENCODER = new DatagramDnsQueryEncoder();
-
- final DnsServerAddresses nameServerAddresses;
- final Future channelFuture;
- final DatagramChannel ch;
-
- /**
- * Manages the {@link DnsQueryContext}s in progress and their query IDs.
- */
- final DnsQueryContextManager queryContextManager = new DnsQueryContextManager();
-
- /**
- * Cache for {@link #doResolve(String, Promise)} and {@link #doResolveAll(String, Promise)}.
- */
- private final DnsCache resolveCache;
-
- private final FastThreadLocal nameServerAddrStream =
- new FastThreadLocal() {
- @Override
- protected DnsServerAddressStream initialValue() throws Exception {
- return nameServerAddresses.stream();
- }
- };
-
- private final long queryTimeoutMillis;
- private final int maxQueriesPerResolve;
- private final boolean traceEnabled;
- private final InternetProtocolFamily[] resolvedAddressTypes;
- private final boolean recursionDesired;
- private final int maxPayloadSize;
- private final boolean optResourceEnabled;
- private final HostsFileEntriesResolver hostsFileEntriesResolver;
- private final String[] searchDomains;
- private final int ndots;
-
- /**
- * Creates a new DNS-based name resolver that communicates with the specified list of DNS servers.
- *
- * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS servers
- * @param channelFactory the {@link ChannelFactory} that will create a {@link DatagramChannel}
- * @param nameServerAddresses the addresses of the DNS server. For each DNS query, a new stream is created from
- * this to determine which DNS server should be contacted for the next retry in case
- * of failure.
- * @param resolveCache the DNS resolved entries cache
- * @param queryTimeoutMillis timeout of each DNS query in millis
- * @param resolvedAddressTypes list of the protocol families
- * @param recursionDesired if recursion desired flag must be set
- * @param maxQueriesPerResolve the maximum allowed number of DNS queries for a given name resolution
- * @param traceEnabled if trace is enabled
- * @param maxPayloadSize the capacity of the datagram packet buffer
- * @param optResourceEnabled if automatic inclusion of a optional records is enabled
- * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to check for local aliases
- * @param searchDomains the list of search domain
- * @param ndots the ndots value
- */
- public DnsNameResolver(
- EventLoop eventLoop,
- ChannelFactory extends DatagramChannel> channelFactory,
- DnsServerAddresses nameServerAddresses,
- final DnsCache resolveCache,
- long queryTimeoutMillis,
- InternetProtocolFamily[] resolvedAddressTypes,
- boolean recursionDesired,
- int maxQueriesPerResolve,
- boolean traceEnabled,
- int maxPayloadSize,
- boolean optResourceEnabled,
- HostsFileEntriesResolver hostsFileEntriesResolver,
- String[] searchDomains,
- int ndots) {
-
- super(eventLoop);
- checkNotNull(channelFactory, "channelFactory");
- this.nameServerAddresses = checkNotNull(nameServerAddresses, "nameServerAddresses");
- this.queryTimeoutMillis = checkPositive(queryTimeoutMillis, "queryTimeoutMillis");
- this.resolvedAddressTypes = checkNonEmpty(resolvedAddressTypes, "resolvedAddressTypes");
- this.recursionDesired = recursionDesired;
- this.maxQueriesPerResolve = checkPositive(maxQueriesPerResolve, "maxQueriesPerResolve");
- this.traceEnabled = traceEnabled;
- this.maxPayloadSize = checkPositive(maxPayloadSize, "maxPayloadSize");
- this.optResourceEnabled = optResourceEnabled;
- this.hostsFileEntriesResolver = checkNotNull(hostsFileEntriesResolver, "hostsFileEntriesResolver");
- this.resolveCache = resolveCache;
- this.searchDomains = checkNotNull(searchDomains, "searchDomains").clone();
- this.ndots = checkPositiveOrZero(ndots, "ndots");
-
- Bootstrap b = new Bootstrap();
- b.group(executor());
- b.channelFactory(channelFactory);
- b.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
- final DnsResponseHandler responseHandler = new DnsResponseHandler(executor().newPromise());
- b.handler(new ChannelInitializer() {
- @Override
- protected void initChannel(DatagramChannel ch) throws Exception {
- ch.pipeline().addLast(DECODER, ENCODER, responseHandler);
- }
- });
-
- channelFuture = responseHandler.channelActivePromise;
- ch = (DatagramChannel) b.register().channel();
- ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize));
-
- ch.closeFuture().addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- resolveCache.clear();
- }
- });
- }
-
- /**
- * Returns the resolution cache.
- */
- public DnsCache resolveCache() {
- return resolveCache;
- }
-
- /**
- * Returns the timeout of each DNS query performed by this resolver (in milliseconds).
- * The default value is 5 seconds.
- */
- public long queryTimeoutMillis() {
- return queryTimeoutMillis;
- }
-
- /**
- * Returns the list of the protocol families of the address resolved by {@link #resolve(String)}
- * in the order of preference.
- * The default value depends on the value of the system property {@code "java.net.preferIPv6Addresses"}.
- */
- public List resolvedAddressTypes() {
- return Arrays.asList(resolvedAddressTypes);
- }
-
- InternetProtocolFamily[] resolveAddressTypesUnsafe() {
- return resolvedAddressTypes;
- }
-
- final String[] searchDomains() {
- return searchDomains;
- }
-
- final int ndots() {
- return ndots;
- }
-
- /**
- * Returns {@code true} if and only if this resolver sends a DNS query with the RD (recursion desired) flag set.
- * The default value is {@code true}.
- */
- public boolean isRecursionDesired() {
- return recursionDesired;
- }
-
- /**
- * Returns the maximum allowed number of DNS queries to send when resolving a host name.
- * The default value is {@code 8}.
- */
- public int maxQueriesPerResolve() {
- return maxQueriesPerResolve;
- }
-
- /**
- * Returns if this resolver should generate the detailed trace information in an exception message so that
- * it is easier to understand the cause of resolution failure. The default value if {@code true}.
- */
- public boolean isTraceEnabled() {
- return traceEnabled;
- }
-
- /**
- * Returns the capacity of the datagram packet buffer (in bytes). The default value is {@code 4096} bytes.
- */
- public int maxPayloadSize() {
- return maxPayloadSize;
- }
-
- /**
- * Returns the automatic inclusion of a optional records that tries to give the remote DNS server a hint about how
- * much data the resolver can read per response is enabled.
- */
- public boolean isOptResourceEnabled() {
- return optResourceEnabled;
- }
-
- /**
- * Returns the component that tries to resolve hostnames against the hosts file prior to asking to
- * remotes DNS servers.
- */
- public HostsFileEntriesResolver hostsFileEntriesResolver() {
- return hostsFileEntriesResolver;
- }
-
- /**
- * Closes the internal datagram channel used for sending and receiving DNS messages, and clears all DNS resource
- * records from the cache. Attempting to send a DNS query or to resolve a domain name will fail once this method
- * has been called.
- */
- @Override
- public void close() {
- ch.close();
- }
-
- @Override
- protected EventLoop executor() {
- return (EventLoop) super.executor();
- }
-
- private InetAddress resolveHostsFileEntry(String hostname) {
- if (hostsFileEntriesResolver == null) {
- return null;
- } else {
- InetAddress address = hostsFileEntriesResolver.address(hostname);
- if (address == null && PlatformDependent.isWindows() && LOCALHOST.equalsIgnoreCase(hostname)) {
- // If we tried to resolve localhost we need workaround that windows removed localhost from its
- // hostfile in later versions.
- // See https://github.com/netty/netty/issues/5386
- return LOCALHOST_ADDRESS;
- }
- return address;
- }
- }
-
- @Override
- protected void doResolve(String inetHost, Promise promise) throws Exception {
- doResolve(inetHost, promise, resolveCache);
- }
-
- /**
- * Hook designed for extensibility so one can pass a different cache on each resolution attempt
- * instead of using the global one.
- */
- protected void doResolve(String inetHost,
- Promise promise,
- DnsCache resolveCache) throws Exception {
- final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
- if (bytes != null) {
- // The inetHost is actually an ipaddress.
- promise.setSuccess(InetAddress.getByAddress(bytes));
- return;
- }
-
- final String hostname = hostname(inetHost);
-
- InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
- if (hostsFileEntry != null) {
- promise.setSuccess(hostsFileEntry);
- return;
- }
-
- if (!doResolveCached(hostname, promise, resolveCache)) {
- doResolveUncached(hostname, promise, resolveCache);
- }
- }
-
- private boolean doResolveCached(String hostname,
- Promise promise,
- DnsCache resolveCache) {
- final List cachedEntries = resolveCache.get(hostname);
- if (cachedEntries == null || cachedEntries.isEmpty()) {
- return false;
- }
-
- InetAddress address = null;
- Throwable cause = null;
- synchronized (cachedEntries) {
- final int numEntries = cachedEntries.size();
- assert numEntries > 0;
-
- if (cachedEntries.get(0).cause() != null) {
- cause = cachedEntries.get(0).cause();
- } else {
- // Find the first entry with the preferred address type.
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- for (int i = 0; i < numEntries; i++) {
- final DnsCacheEntry e = cachedEntries.get(i);
- if (addressMatchFamily(e.address(), f)) {
- address = e.address();
- break;
- }
- }
- }
- }
- }
-
- if (address != null) {
- setSuccess(promise, address);
- } else if (cause != null) {
- if (!promise.tryFailure(cause)) {
- logger.warn("Failed to notify failure to a promise: {}", promise, cause);
- }
- } else {
- return false;
- }
-
- return true;
- }
-
- private static void setSuccess(Promise promise, InetAddress result) {
- if (!promise.trySuccess(result)) {
- logger.warn("Failed to notify success ({}) to a promise: {}", result, promise);
- }
- }
-
- private void doResolveUncached(String hostname,
- Promise promise,
- DnsCache resolveCache) {
- SingleResolverContext ctx = new SingleResolverContext(this, hostname, resolveCache);
- ctx.resolve(promise);
- }
-
- final class SingleResolverContext extends DnsNameResolverContext {
-
- SingleResolverContext(DnsNameResolver parent, String hostname, DnsCache resolveCache) {
- super(parent, hostname, resolveCache);
- }
-
- @Override
- DnsNameResolverContext newResolverContext(DnsNameResolver parent,
- String hostname, DnsCache resolveCache) {
- return new SingleResolverContext(parent, hostname, resolveCache);
- }
-
- @Override
- boolean finishResolve(
- InternetProtocolFamily f, List resolvedEntries,
- Promise promise) {
-
- final int numEntries = resolvedEntries.size();
- for (int i = 0; i < numEntries; i++) {
- final InetAddress a = resolvedEntries.get(i).address();
- if (addressMatchFamily(a, f)) {
- setSuccess(promise, a);
- return true;
- }
- }
- return false;
- }
- }
-
- @Override
- protected void doResolveAll(String inetHost, Promise> promise) throws Exception {
- doResolveAll(inetHost, promise, resolveCache);
- }
-
- /**
- * Hook designed for extensibility so one can pass a different cache on each resolution attempt
- * instead of using the global one.
- */
- protected void doResolveAll(String inetHost,
- Promise> promise,
- DnsCache resolveCache) throws Exception {
-
- final byte[] bytes = NetUtil.createByteArrayFromIpAddressString(inetHost);
- if (bytes != null) {
- // The unresolvedAddress was created via a String that contains an ipaddress.
- promise.setSuccess(Collections.singletonList(InetAddress.getByAddress(bytes)));
- return;
- }
-
- final String hostname = hostname(inetHost);
-
- InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
- if (hostsFileEntry != null) {
- promise.setSuccess(Collections.singletonList(hostsFileEntry));
- return;
- }
-
- if (!doResolveAllCached(hostname, promise, resolveCache)) {
- doResolveAllUncached(hostname, promise, resolveCache);
- }
- }
-
- private boolean doResolveAllCached(String hostname,
- Promise> promise,
- DnsCache resolveCache) {
- final List cachedEntries = resolveCache.get(hostname);
- if (cachedEntries == null || cachedEntries.isEmpty()) {
- return false;
- }
-
- List result = null;
- Throwable cause = null;
- synchronized (cachedEntries) {
- final int numEntries = cachedEntries.size();
- assert numEntries > 0;
-
- if (cachedEntries.get(0).cause() != null) {
- cause = cachedEntries.get(0).cause();
- } else {
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- for (int i = 0; i < numEntries; i++) {
- final DnsCacheEntry e = cachedEntries.get(i);
- if (addressMatchFamily(e.address(), f)) {
- if (result == null) {
- result = new ArrayList(numEntries);
- }
- result.add(e.address());
- }
- }
- }
- }
- }
-
- if (result != null) {
- promise.trySuccess(result);
- } else if (cause != null) {
- promise.tryFailure(cause);
- } else {
- return false;
- }
-
- return true;
- }
-
- final class ListResolverContext extends DnsNameResolverContext> {
- ListResolverContext(DnsNameResolver parent, String hostname, DnsCache resolveCache) {
- super(parent, hostname, resolveCache);
- }
-
- @Override
- DnsNameResolverContext> newResolverContext(DnsNameResolver parent, String hostname,
- DnsCache resolveCache) {
- return new ListResolverContext(parent, hostname, resolveCache);
- }
-
- @Override
- boolean finishResolve(
- InternetProtocolFamily f, List resolvedEntries,
- Promise> promise) {
-
- List result = null;
- final int numEntries = resolvedEntries.size();
- for (int i = 0; i < numEntries; i++) {
- final InetAddress a = resolvedEntries.get(i).address();
- if (addressMatchFamily(a, f)) {
- if (result == null) {
- result = new ArrayList(numEntries);
- }
- result.add(a);
- }
- }
-
- if (result != null) {
- promise.trySuccess(result);
- return true;
- }
- return false;
- }
- }
-
- private void doResolveAllUncached(String hostname,
- Promise> promise,
- DnsCache resolveCache) {
- DnsNameResolverContext> ctx = new ListResolverContext(this, hostname, resolveCache);
- ctx.resolve(promise);
- }
-
- private static String hostname(String inetHost) {
- String hostname = IDN.toASCII(inetHost);
- // Check for http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6894622
- if (StringUtil2.endsWith(inetHost, '.') && !StringUtil2.endsWith(hostname, '.')) {
- hostname += ".";
- }
- return hostname;
- }
-
- /**
- * Sends a DNS query with the specified question.
- */
- public Future> query(DnsQuestion question) {
- return query(nextNameServerAddress(), question);
- }
-
- /**
- * Sends a DNS query with the specified question with additional records.
- */
- public Future> query(
- DnsQuestion question, Iterable additional) {
- return query(nextNameServerAddress(), question, additional);
- }
-
- /**
- * Sends a DNS query with the specified question.
- */
- public Future> query(
- DnsQuestion question, Promise> promise) {
- return query(nextNameServerAddress(), question, Collections.emptyList(), promise);
- }
-
- private InetSocketAddress nextNameServerAddress() {
- return nameServerAddrStream.get().next();
- }
-
- /**
- * Sends a DNS query with the specified question using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question) {
-
- return query0(nameServerAddr, question, Collections.emptyList(),
- ch.eventLoop().>newPromise());
- }
-
- /**
- * Sends a DNS query with the specified question with additional records using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question, Iterable additional) {
-
- return query0(nameServerAddr, question, additional,
- ch.eventLoop().>newPromise());
- }
-
- /**
- * Sends a DNS query with the specified question using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Promise> promise) {
-
- return query0(nameServerAddr, question, Collections.emptyList(), promise);
- }
-
- /**
- * Sends a DNS query with the specified question with additional records using the specified name server list.
- */
- public Future> query(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- return query0(nameServerAddr, question, additional, promise);
- }
-
- private Future> query0(
- InetSocketAddress nameServerAddr, DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- final Promise> castPromise = cast(
- checkNotNull(promise, "promise"));
- try {
- new DnsQueryContext(this, nameServerAddr, question, additional, castPromise).query();
- return castPromise;
- } catch (Exception e) {
- return castPromise.setFailure(e);
- }
- }
-
- @SuppressWarnings("unchecked")
- private static Promise> cast(Promise> promise) {
- return (Promise>) promise;
- }
-
- private final class DnsResponseHandler extends ChannelInboundHandlerAdapter {
-
- private final Promise channelActivePromise;
-
- DnsResponseHandler(Promise channelActivePromise) {
- this.channelActivePromise = channelActivePromise;
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- try {
- final DatagramDnsResponse res = (DatagramDnsResponse) msg;
- final int queryId = res.id();
-
- if (logger.isDebugEnabled()) {
- logger.debug("{} RECEIVED: [{}: {}], {}", ch, queryId, res.sender(), res);
- }
-
- final DnsQueryContext qCtx = queryContextManager.get(res.sender(), queryId);
- if (qCtx == null) {
- logger.warn("{} Received a DNS response with an unknown ID: {}", ch, queryId);
- return;
- }
-
- qCtx.finish(res);
- } finally {
- ReferenceCountUtil.safeRelease(msg);
- }
- }
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- super.channelActive(ctx);
- channelActivePromise.setSuccess(ctx.channel());
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- logger.warn("{} Unexpected exception: ", ch, cause);
- }
- }
-
- static boolean addressMatchFamily(InetAddress a, InternetProtocolFamily f) {
- return (f == InternetProtocolFamily.IPv4 && a instanceof Inet4Address) || f == InternetProtocolFamily.IPv6;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java
deleted file mode 100644
index 3386624800..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverBuilder.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import static io.netty.util.internal.ObjectUtil2.intValue;
-
-import io.netty.bootstrap.ChannelFactory;
-import io.netty.channel.EventLoop;
-import io.netty.channel.ReflectiveChannelFactory;
-import io.netty.channel.socket.DatagramChannel;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.resolver.HostsFileEntriesResolver;
-import io.netty.util.internal.InternalThreadLocalMap;
-
-import java.util.List;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-/**
- * A {@link DnsNameResolver} builder.
- */
-public final class DnsNameResolverBuilder {
-
- private final EventLoop eventLoop;
- private ChannelFactory extends DatagramChannel> channelFactory;
- private DnsServerAddresses nameServerAddresses = DnsServerAddresses.defaultAddresses();
- private DnsCache resolveCache;
- private Integer minTtl;
- private Integer maxTtl;
- private Integer negativeTtl;
- private long queryTimeoutMillis = 5000;
- private InternetProtocolFamily[] resolvedAddressTypes = DnsNameResolver.DEFAULT_RESOLVE_ADDRESS_TYPES;
- private boolean recursionDesired = true;
- private int maxQueriesPerResolve = 16;
- private boolean traceEnabled;
- private int maxPayloadSize = 4096;
- private boolean optResourceEnabled = true;
- private HostsFileEntriesResolver hostsFileEntriesResolver = HostsFileEntriesResolver.DEFAULT;
- private String[] searchDomains = DnsNameResolver.DEFAULT_SEACH_DOMAINS;
- private int ndots = 1;
-
- /**
- * Creates a new builder.
- *
- * @param eventLoop the {@link EventLoop} the {@link EventLoop} which will perform the communication with the DNS
- * servers.
- */
- public DnsNameResolverBuilder(EventLoop eventLoop) {
- this.eventLoop = eventLoop;
- }
-
- /**
- * Sets the {@link ChannelFactory} that will create a {@link DatagramChannel}.
- *
- * @param channelFactory the {@link ChannelFactory}
- * @return {@code this}
- */
- public DnsNameResolverBuilder channelFactory(ChannelFactory extends DatagramChannel> channelFactory) {
- this.channelFactory = channelFactory;
- return this;
- }
-
- /**
- * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type.
- * Use as an alternative to {@link #channelFactory(ChannelFactory)}.
- *
- * @param channelType the type
- * @return {@code this}
- */
- public DnsNameResolverBuilder channelType(Class extends DatagramChannel> channelType) {
- return channelFactory(new ReflectiveChannelFactory(channelType));
- }
-
- /**
- * Sets the addresses of the DNS server.
- *
- * @param nameServerAddresses the DNS server addresses
- * @return {@code this}
- */
- public DnsNameResolverBuilder nameServerAddresses(DnsServerAddresses nameServerAddresses) {
- this.nameServerAddresses = nameServerAddresses;
- return this;
- }
-
- /**
- * Sets the cache for resolution results.
- *
- * @param resolveCache the DNS resolution results cache
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolveCache(DnsCache resolveCache) {
- this.resolveCache = resolveCache;
- return this;
- }
-
- /**
- * Sets the minimum and maximum TTL of the cached DNS resource records (in seconds). If the TTL of the DNS
- * resource record returned by the DNS server is less than the minimum TTL or greater than the maximum TTL,
- * this resolver will ignore the TTL from the DNS server and use the minimum TTL or the maximum TTL instead
- * respectively.
- * The default value is {@code 0} and {@link Integer#MAX_VALUE}, which practically tells this resolver to
- * respect the TTL from the DNS server.
- *
- * @param minTtl the minimum TTL
- * @param maxTtl the maximum TTL
- * @return {@code this}
- */
- public DnsNameResolverBuilder ttl(int minTtl, int maxTtl) {
- this.maxTtl = maxTtl;
- this.minTtl = minTtl;
- return this;
- }
-
- /**
- * Sets the TTL of the cache for the failed DNS queries (in seconds).
- *
- * @param negativeTtl the TTL for failed cached queries
- * @return {@code this}
- */
- public DnsNameResolverBuilder negativeTtl(int negativeTtl) {
- this.negativeTtl = negativeTtl;
- return this;
- }
-
- /**
- * Sets the timeout of each DNS query performed by this resolver (in milliseconds).
- *
- * @param queryTimeoutMillis the query timeout
- * @return {@code this}
- */
- public DnsNameResolverBuilder queryTimeoutMillis(long queryTimeoutMillis) {
- this.queryTimeoutMillis = queryTimeoutMillis;
- return this;
- }
-
- /**
- * Sets the list of the protocol families of the address resolved.
- * Usually, both {@link InternetProtocolFamily#IPv4} and {@link InternetProtocolFamily#IPv6} are specified in
- * the order of preference. To enforce the resolve to retrieve the address of a specific protocol family,
- * specify only a single {@link InternetProtocolFamily}.
- *
- * @param resolvedAddressTypes the address types
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolvedAddressTypes(InternetProtocolFamily... resolvedAddressTypes) {
- checkNotNull(resolvedAddressTypes, "resolvedAddressTypes");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(InternetProtocolFamily.values().length);
-
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- if (list.isEmpty()) {
- throw new IllegalArgumentException("no protocol family specified");
- }
-
- this.resolvedAddressTypes = list.toArray(new InternetProtocolFamily[list.size()]);
-
- return this;
- }
-
- /**
- * Sets the list of the protocol families of the address resolved.
- * Usually, both {@link InternetProtocolFamily#IPv4} and {@link InternetProtocolFamily#IPv6} are specified in
- * the order of preference. To enforce the resolve to retrieve the address of a specific protocol family,
- * specify only a single {@link InternetProtocolFamily}.
- *
- * @param resolvedAddressTypes the address types
- * @return {@code this}
- */
- public DnsNameResolverBuilder resolvedAddressTypes(Iterable resolvedAddressTypes) {
- checkNotNull(resolvedAddressTypes, "resolveAddressTypes");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(InternetProtocolFamily.values().length);
-
- for (InternetProtocolFamily f : resolvedAddressTypes) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- if (list.isEmpty()) {
- throw new IllegalArgumentException("no protocol family specified");
- }
-
- this.resolvedAddressTypes = list.toArray(new InternetProtocolFamily[list.size()]);
-
- return this;
- }
-
- /**
- * Sets if this resolver has to send a DNS query with the RD (recursion desired) flag set.
- *
- * @param recursionDesired true if recursion is desired
- * @return {@code this}
- */
- public DnsNameResolverBuilder recursionDesired(boolean recursionDesired) {
- this.recursionDesired = recursionDesired;
- return this;
- }
-
- /**
- * Sets the maximum allowed number of DNS queries to send when resolving a host name.
- *
- * @param maxQueriesPerResolve the max number of queries
- * @return {@code this}
- */
- public DnsNameResolverBuilder maxQueriesPerResolve(int maxQueriesPerResolve) {
- this.maxQueriesPerResolve = maxQueriesPerResolve;
- return this;
- }
-
- /**
- * Sets if this resolver should generate the detailed trace information in an exception message so that
- * it is easier to understand the cause of resolution failure.
- *
- * @param traceEnabled true if trace is enabled
- * @return {@code this}
- */
- public DnsNameResolverBuilder traceEnabled(boolean traceEnabled) {
- this.traceEnabled = traceEnabled;
- return this;
- }
-
- /**
- * Sets the capacity of the datagram packet buffer (in bytes). The default value is {@code 4096} bytes.
- *
- * @param maxPayloadSize the capacity of the datagram packet buffer
- * @return {@code this}
- */
- public DnsNameResolverBuilder maxPayloadSize(int maxPayloadSize) {
- this.maxPayloadSize = maxPayloadSize;
- return this;
- }
-
- /**
- * Enable the automatic inclusion of a optional records that tries to give the remote DNS server a hint about
- * how much data the resolver can read per response. Some DNSServer may not support this and so fail to answer
- * queries. If you find problems you may want to disable this.
- *
- * @param optResourceEnabled if optional records inclusion is enabled
- * @return {@code this}
- */
- public DnsNameResolverBuilder optResourceEnabled(boolean optResourceEnabled) {
- this.optResourceEnabled = optResourceEnabled;
- return this;
- }
-
- /**
- * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to first check
- * if the hostname is locally aliased.
- * @return {@code this}
- */
- public DnsNameResolverBuilder hostsFileEntriesResolver(HostsFileEntriesResolver hostsFileEntriesResolver) {
- this.hostsFileEntriesResolver = hostsFileEntriesResolver;
- return this;
- }
-
- /**
- * Set the list of search domains of the resolver.
- *
- * @param searchDomains the search domains
- * @return {@code this}
- */
- public DnsNameResolverBuilder searchDomains(Iterable searchDomains) {
- checkNotNull(searchDomains, "searchDomains");
-
- final List list =
- InternalThreadLocalMap.get().arrayList(4);
-
- for (String f : searchDomains) {
- if (f == null) {
- break;
- }
-
- // Avoid duplicate entries.
- if (list.contains(f)) {
- continue;
- }
-
- list.add(f);
- }
-
- this.searchDomains = list.toArray(new String[list.size()]);
- return this;
- }
-
- /**
- * Set the number of dots which must appear in a name before an initial absolute query is made.
- * The default value is {@code 1}.
- *
- * @param ndots the ndots value
- * @return {@code this}
- */
- public DnsNameResolverBuilder ndots(int ndots) {
- this.ndots = ndots;
- return this;
- }
-
- /**
- * Returns a new {@link DnsNameResolver} instance.
- *
- * @return a {@link DnsNameResolver}
- */
- public DnsNameResolver build() {
-
- if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
- throw new IllegalStateException("resolveCache and TTLs are mutually exclusive");
- }
-
- DnsCache cache = resolveCache != null ? resolveCache :
- new DefaultDnsCache(intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE), intValue(negativeTtl, 0));
-
- return new DnsNameResolver(
- eventLoop,
- channelFactory,
- nameServerAddresses,
- cache,
- queryTimeoutMillis,
- resolvedAddressTypes,
- recursionDesired,
- maxQueriesPerResolve,
- traceEnabled,
- maxPayloadSize,
- optResourceEnabled,
- hostsFileEntriesResolver,
- searchDomains,
- ndots);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java
deleted file mode 100644
index 7c663f7ae8..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverContext.java
+++ /dev/null
@@ -1,547 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufHolder;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.socket.InternetProtocolFamily;
-import io.netty.handler.codec.CorruptedFrameException;
-import io.netty.handler.codec.dns.DefaultDnsQuestion;
-import io.netty.handler.codec.dns.DefaultDnsRecordDecoder;
-import io.netty.handler.codec.dns.DnsResponseCode;
-import io.netty.handler.codec.dns.DnsSection;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsRawRecord;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DnsRecordType;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.util.ReferenceCountUtil;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.internal.StringUtil;
-import io.netty.util.internal.StringUtil2;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-abstract class DnsNameResolverContext {
-
- private static final int INADDRSZ4 = 4;
- private static final int INADDRSZ6 = 16;
-
- private static final FutureListener> RELEASE_RESPONSE =
- new FutureListener>() {
- @Override
- public void operationComplete(Future> future) {
- if (future.isSuccess()) {
- future.getNow().release();
- }
- }
- };
-
- private final DnsNameResolver parent;
- private final DnsServerAddressStream nameServerAddrs;
- private final String hostname;
- protected String pristineHostname;
- private final DnsCache resolveCache;
- private final boolean traceEnabled;
- private final int maxAllowedQueries;
- private final InternetProtocolFamily[] resolveAddressTypes;
-
- private final Set>> queriesInProgress =
- Collections.newSetFromMap(
- new IdentityHashMap>, Boolean>());
-
- private List resolvedEntries;
- private StringBuilder trace;
- private int allowedQueries;
- private boolean triedCNAME;
-
- protected DnsNameResolverContext(DnsNameResolver parent,
- String hostname,
- DnsCache resolveCache) {
- this.parent = parent;
- this.hostname = hostname;
- this.resolveCache = resolveCache;
-
- nameServerAddrs = parent.nameServerAddresses.stream();
- maxAllowedQueries = parent.maxQueriesPerResolve();
- resolveAddressTypes = parent.resolveAddressTypesUnsafe();
- traceEnabled = parent.isTraceEnabled();
- allowedQueries = maxAllowedQueries;
- }
-
- void resolve(Promise promise) {
- boolean directSearch = parent.searchDomains().length == 0 || StringUtil2.endsWith(hostname, '.');
- if (directSearch) {
- internalResolve(promise);
- } else {
- final Promise original = promise;
- promise = parent.executor().newPromise();
- promise.addListener(new FutureListener() {
- int count;
- @Override
- public void operationComplete(Future future) throws Exception {
- if (future.isSuccess()) {
- original.trySuccess(future.getNow());
- } else if (count < parent.searchDomains().length) {
- String searchDomain = parent.searchDomains()[count++];
- Promise nextPromise = parent.executor().newPromise();
- String nextHostname = DnsNameResolverContext.this.hostname + "." + searchDomain;
- DnsNameResolverContext nextContext = newResolverContext(parent,
- nextHostname, resolveCache);
- nextContext.pristineHostname = hostname;
- nextContext.internalResolve(nextPromise);
- nextPromise.addListener(this);
- } else {
- original.tryFailure(future.cause());
- }
- }
- });
- if (parent.ndots() == 0) {
- internalResolve(promise);
- } else {
- int dots = 0;
- for (int idx = hostname.length() - 1; idx >= 0; idx--) {
- if (hostname.charAt(idx) == '.' && ++dots >= parent.ndots()) {
- internalResolve(promise);
- return;
- }
- }
- promise.tryFailure(new UnknownHostException(hostname));
- }
- }
- }
-
- private void internalResolve(Promise promise) {
- InetSocketAddress nameServerAddrToTry = nameServerAddrs.next();
- for (InternetProtocolFamily f: resolveAddressTypes) {
- final DnsRecordType type;
- switch (f) {
- case IPv4:
- type = DnsRecordType.A;
- break;
- case IPv6:
- type = DnsRecordType.AAAA;
- break;
- default:
- throw new Error();
- }
-
- query(nameServerAddrToTry, new DefaultDnsQuestion(hostname, type), promise);
- }
- }
-
- private void query(InetSocketAddress nameServerAddr, final DnsQuestion question, final Promise promise) {
- if (allowedQueries == 0 || promise.isCancelled()) {
- tryToFinishResolve(promise);
- return;
- }
-
- allowedQueries --;
-
- final Future> f = parent.query(nameServerAddr, question);
- queriesInProgress.add(f);
-
- f.addListener(new FutureListener>() {
- @Override
- public void operationComplete(Future> future) {
- queriesInProgress.remove(future);
-
- if (promise.isDone() || future.isCancelled()) {
- return;
- }
-
- try {
- if (future.isSuccess()) {
- onResponse(question, future.getNow(), promise);
- } else {
- // Server did not respond or I/O error occurred; try again.
- if (traceEnabled) {
- addTrace(future.cause());
- }
- query(nameServerAddrs.next(), question, promise);
- }
- } finally {
- tryToFinishResolve(promise);
- }
- }
- });
- }
-
- void onResponse(final DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
- try {
- final DnsResponse res = envelope.content();
- final DnsResponseCode code = res.code();
- if (code == DnsResponseCode.NOERROR) {
- final DnsRecordType type = question.type();
- if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
- onResponseAorAAAA(type, question, envelope, promise);
- } else if (type == DnsRecordType.CNAME) {
- onResponseCNAME(question, envelope, promise);
- }
- return;
- }
-
- if (traceEnabled) {
- addTrace(envelope.sender(),
- "response code: " + code + " with " + res.count(DnsSection.ANSWER) + " answer(s) and " +
- res.count(DnsSection.AUTHORITY) + " authority resource(s)");
- }
-
- // Retry with the next server if the server did not tell us that the domain does not exist.
- if (code != DnsResponseCode.NXDOMAIN) {
- query(nameServerAddrs.next(), question, promise);
- }
- } finally {
- ReferenceCountUtil.safeRelease(envelope);
- }
- }
-
- private void onResponseAorAAAA(
- DnsRecordType qType, DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
-
- // We often get a bunch of CNAMES as well when we asked for A/AAAA.
- final DnsResponse response = envelope.content();
- final Map cnames = buildAliasMap(response);
- final int answerCount = response.count(DnsSection.ANSWER);
-
- boolean found = false;
- for (int i = 0; i < answerCount; i ++) {
- final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
- final DnsRecordType type = r.type();
- if (type != DnsRecordType.A && type != DnsRecordType.AAAA) {
- continue;
- }
-
- final String qName = question.name().toLowerCase(Locale.US);
- final String rName = r.name().toLowerCase(Locale.US);
-
- // Make sure the record is for the questioned domain.
- if (!rName.equals(qName)) {
- // Even if the record's name is not exactly same, it might be an alias defined in the CNAME records.
- String resolved = qName;
- do {
- resolved = cnames.get(resolved);
- if (rName.equals(resolved)) {
- break;
- }
- } while (resolved != null);
-
- if (resolved == null) {
- continue;
- }
- }
-
- if (!(r instanceof DnsRawRecord)) {
- continue;
- }
-
- final ByteBuf content = ((ByteBufHolder) r).content();
- final int contentLen = content.readableBytes();
- if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) {
- continue;
- }
-
- final byte[] addrBytes = new byte[contentLen];
- content.getBytes(content.readerIndex(), addrBytes);
-
- final InetAddress resolved;
- try {
- resolved = InetAddress.getByAddress(hostname, addrBytes);
- } catch (UnknownHostException e) {
- // Should never reach here.
- throw new Error(e);
- }
-
- if (resolvedEntries == null) {
- resolvedEntries = new ArrayList(8);
- }
-
- final DnsCacheEntry e = new DnsCacheEntry(hostname, resolved);
- resolveCache.cache(hostname, resolved, r.timeToLive(), parent.ch.eventLoop());
- resolvedEntries.add(e);
- found = true;
-
- // Note that we do not break from the loop here, so we decode/cache all A/AAAA records.
- }
-
- if (found) {
- return;
- }
-
- if (traceEnabled) {
- addTrace(envelope.sender(), "no matching " + qType + " record found");
- }
-
- // We aked for A/AAAA but we got only CNAME.
- if (!cnames.isEmpty()) {
- onResponseCNAME(question, envelope, cnames, false, promise);
- }
- }
-
- private void onResponseCNAME(DnsQuestion question, AddressedEnvelope envelope,
- Promise promise) {
- onResponseCNAME(question, envelope, buildAliasMap(envelope.content()), true, promise);
- }
-
- private void onResponseCNAME(
- DnsQuestion question, AddressedEnvelope response,
- Map cnames, boolean trace, Promise promise) {
-
- // Resolve the host name in the question into the real host name.
- final String name = question.name().toLowerCase(Locale.US);
- String resolved = name;
- boolean found = false;
- while (!cnames.isEmpty()) { // Do not attempt to call Map.remove() when the Map is empty
- // because it can be Collections.emptyMap()
- // whose remove() throws a UnsupportedOperationException.
- final String next = cnames.remove(resolved);
- if (next != null) {
- found = true;
- resolved = next;
- } else {
- break;
- }
- }
-
- if (found) {
- followCname(response.sender(), name, resolved, promise);
- } else if (trace && traceEnabled) {
- addTrace(response.sender(), "no matching CNAME record found");
- }
- }
-
- private static Map buildAliasMap(DnsResponse response) {
- final int answerCount = response.count(DnsSection.ANSWER);
- Map cnames = null;
- for (int i = 0; i < answerCount; i ++) {
- final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
- final DnsRecordType type = r.type();
- if (type != DnsRecordType.CNAME) {
- continue;
- }
-
- if (!(r instanceof DnsRawRecord)) {
- continue;
- }
-
- final ByteBuf recordContent = ((ByteBufHolder) r).content();
- final String domainName = decodeDomainName(recordContent);
- if (domainName == null) {
- continue;
- }
-
- if (cnames == null) {
- cnames = new HashMap();
- }
-
- cnames.put(r.name().toLowerCase(Locale.US), domainName.toLowerCase(Locale.US));
- }
-
- return cnames != null? cnames : Collections.emptyMap();
- }
-
- void tryToFinishResolve(Promise promise) {
- if (!queriesInProgress.isEmpty()) {
- // There are still some queries we did not receive responses for.
- if (gotPreferredAddress()) {
- // But it's OK to finish the resolution process if we got a resolved address of the preferred type.
- finishResolve(promise);
- }
-
- // We did not get any resolved address of the preferred type, so we can't finish the resolution process.
- return;
- }
-
- // There are no queries left to try.
- if (resolvedEntries == null) {
- // .. and we could not find any A/AAAA records.
- if (!triedCNAME) {
- // As the last resort, try to query CNAME, just in case the name server has it.
- triedCNAME = true;
- query(nameServerAddrs.next(), new DefaultDnsQuestion(hostname, DnsRecordType.CNAME), promise);
- return;
- }
- }
-
- // We have at least one resolved address or tried CNAME as the last resort..
- finishResolve(promise);
- }
-
- private boolean gotPreferredAddress() {
- if (resolvedEntries == null) {
- return false;
- }
-
- final int size = resolvedEntries.size();
- switch (resolveAddressTypes[0]) {
- case IPv4:
- for (int i = 0; i < size; i ++) {
- if (resolvedEntries.get(i).address() instanceof Inet4Address) {
- return true;
- }
- }
- break;
- case IPv6:
- for (int i = 0; i < size; i ++) {
- if (resolvedEntries.get(i).address() instanceof Inet6Address) {
- return true;
- }
- }
- break;
- }
-
- return false;
- }
-
- private void finishResolve(Promise promise) {
- if (!queriesInProgress.isEmpty()) {
- // If there are queries in progress, we should cancel it because we already finished the resolution.
- for (Iterator>> i = queriesInProgress.iterator();
- i.hasNext();) {
- Future> f = i.next();
- i.remove();
-
- if (!f.cancel(false)) {
- f.addListener(RELEASE_RESPONSE);
- }
- }
- }
-
- if (resolvedEntries != null) {
- // Found at least one resolved address.
- for (InternetProtocolFamily f: resolveAddressTypes) {
- if (finishResolve(f, resolvedEntries, promise)) {
- return;
- }
- }
- }
-
- // No resolved address found.
- final int tries = maxAllowedQueries - allowedQueries;
- final StringBuilder buf = new StringBuilder(64);
-
- buf.append("failed to resolve '");
- if (pristineHostname != null) {
- buf.append(pristineHostname);
- } else {
- buf.append(hostname);
- }
- buf.append('\'');
- if (tries > 1) {
- if (tries < maxAllowedQueries) {
- buf.append(" after ")
- .append(tries)
- .append(" queries ");
- } else {
- buf.append(". Exceeded max queries per resolve ")
- .append(maxAllowedQueries)
- .append(' ');
- }
- }
- if (trace != null) {
- buf.append(':')
- .append(trace);
- }
- final UnknownHostException cause = new UnknownHostException(buf.toString());
-
- resolveCache.cache(hostname, cause, parent.ch.eventLoop());
- promise.tryFailure(cause);
- }
-
- abstract boolean finishResolve(InternetProtocolFamily f, List resolvedEntries,
- Promise promise);
-
- abstract DnsNameResolverContext newResolverContext(DnsNameResolver parent, String hostname,
- DnsCache resolveCache);
-
- static String decodeDomainName(ByteBuf in) {
- in.markReaderIndex();
- try {
- return DefaultDnsRecordDecoder.decodeName(in);
- } catch (CorruptedFrameException e) {
- // In this case we just return null.
- return null;
- } finally {
- in.resetReaderIndex();
- }
- }
-
- private void followCname(InetSocketAddress nameServerAddr, String name, String cname, Promise promise) {
-
- if (traceEnabled) {
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("\tfrom ");
- trace.append(nameServerAddr);
- trace.append(": ");
- trace.append(name);
- trace.append(" CNAME ");
- trace.append(cname);
- }
-
- final InetSocketAddress nextAddr = nameServerAddrs.next();
- query(nextAddr, new DefaultDnsQuestion(cname, DnsRecordType.A), promise);
- query(nextAddr, new DefaultDnsQuestion(cname, DnsRecordType.AAAA), promise);
- }
-
- private void addTrace(InetSocketAddress nameServerAddr, String msg) {
- assert traceEnabled;
-
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("\tfrom ");
- trace.append(nameServerAddr);
- trace.append(": ");
- trace.append(msg);
- }
-
- private void addTrace(Throwable cause) {
- assert traceEnabled;
-
- if (trace == null) {
- trace = new StringBuilder(128);
- }
-
- trace.append(StringUtil.NEWLINE);
- trace.append("Caused by: ");
- trace.append(cause);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java
deleted file mode 100644
index 05eb8757bd..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolverException.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.ObjectUtil;
-
-import java.net.InetSocketAddress;
-
-/**
- * A {@link RuntimeException} raised when {@link DnsNameResolver} failed to perform a successful query.
- */
-public final class DnsNameResolverException extends RuntimeException {
-
- private static final long serialVersionUID = -8826717909627131850L;
-
- private final InetSocketAddress remoteAddress;
- private final DnsQuestion question;
-
- public DnsNameResolverException(InetSocketAddress remoteAddress, DnsQuestion question, String message) {
- super(message);
- this.remoteAddress = validateRemoteAddress(remoteAddress);
- this.question = validateQuestion(question);
- }
-
- public DnsNameResolverException(
- InetSocketAddress remoteAddress, DnsQuestion question, String message, Throwable cause) {
- super(message, cause);
- this.remoteAddress = validateRemoteAddress(remoteAddress);
- this.question = validateQuestion(question);
- }
-
- private static InetSocketAddress validateRemoteAddress(InetSocketAddress remoteAddress) {
- return ObjectUtil.checkNotNull(remoteAddress, "remoteAddress");
- }
-
- private static DnsQuestion validateQuestion(DnsQuestion question) {
- return ObjectUtil.checkNotNull(question, "question");
- }
-
- /**
- * Returns the {@link InetSocketAddress} of the DNS query that has failed.
- */
- public InetSocketAddress remoteAddress() {
- return remoteAddress;
- }
-
- /**
- * Returns the {@link DnsQuestion} of the DNS query that has failed.
- */
- public DnsQuestion question() {
- return question;
- }
-
- @Override
- public Throwable fillInStackTrace() {
- setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
- return this;
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java
deleted file mode 100644
index 897d2f3b40..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContext.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-package io.netty.resolver.dns;
-
-import io.netty.buffer.Unpooled;
-import io.netty.channel.AddressedEnvelope;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.handler.codec.dns.DatagramDnsQuery;
-import io.netty.handler.codec.dns.DefaultDnsRawRecord;
-import io.netty.handler.codec.dns.DnsQuery;
-import io.netty.handler.codec.dns.DnsQuestion;
-import io.netty.handler.codec.dns.DnsRecord;
-import io.netty.handler.codec.dns.DnsRecordType;
-import io.netty.handler.codec.dns.DnsResponse;
-import io.netty.handler.codec.dns.DnsSection;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.GenericFutureListener;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.concurrent.ScheduledFuture;
-import io.netty.util.internal.StringUtil;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.net.InetSocketAddress;
-import java.util.concurrent.TimeUnit;
-
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-
-final class DnsQueryContext {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsQueryContext.class);
-
- private final DnsNameResolver parent;
- private final Promise> promise;
- private final int id;
- private final DnsQuestion question;
- private final Iterable additional;
- private final DnsRecord optResource;
- private final InetSocketAddress nameServerAddr;
-
- private final boolean recursionDesired;
- private volatile ScheduledFuture> timeoutFuture;
-
- DnsQueryContext(DnsNameResolver parent,
- InetSocketAddress nameServerAddr,
- DnsQuestion question,
- Iterable additional,
- Promise> promise) {
-
- this.parent = checkNotNull(parent, "parent");
- this.nameServerAddr = checkNotNull(nameServerAddr, "nameServerAddr");
- this.question = checkNotNull(question, "question");
- this.additional = checkNotNull(additional, "additional");
- this.promise = checkNotNull(promise, "promise");
- recursionDesired = parent.isRecursionDesired();
- id = parent.queryContextManager.add(this);
-
- if (parent.isOptResourceEnabled()) {
- optResource = new DefaultDnsRawRecord(
- StringUtil.EMPTY_STRING, DnsRecordType.OPT, parent.maxPayloadSize(), 0, Unpooled.EMPTY_BUFFER);
- } else {
- optResource = null;
- }
- }
-
- InetSocketAddress nameServerAddr() {
- return nameServerAddr;
- }
-
- DnsQuestion question() {
- return question;
- }
-
- void query() {
- final DnsQuestion question = question();
- final InetSocketAddress nameServerAddr = nameServerAddr();
- final DatagramDnsQuery query = new DatagramDnsQuery(null, nameServerAddr, id);
-
- query.setRecursionDesired(recursionDesired);
-
- query.addRecord(DnsSection.QUESTION, question);
-
- for (DnsRecord record:additional) {
- query.addRecord(DnsSection.ADDITIONAL, record);
- }
- if (optResource != null) {
- query.addRecord(DnsSection.ADDITIONAL, optResource);
- }
-
- if (logger.isDebugEnabled()) {
- logger.debug("{} WRITE: [{}: {}], {}", parent.ch, id, nameServerAddr, question);
- }
-
- sendQuery(query);
- }
-
- private void sendQuery(final DnsQuery query) {
- if (parent.channelFuture.isDone()) {
- writeQuery(query);
- } else {
- parent.channelFuture.addListener(new GenericFutureListener>() {
- @Override
- public void operationComplete(Future super Channel> future) throws Exception {
- if (future.isSuccess()) {
- writeQuery(query);
- } else {
- promise.tryFailure(future.cause());
- }
- }
- });
- }
- }
-
- private void writeQuery(final DnsQuery query) {
- final ChannelFuture writeFuture = parent.ch.writeAndFlush(query);
- if (writeFuture.isDone()) {
- onQueryWriteCompletion(writeFuture);
- } else {
- writeFuture.addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture future) throws Exception {
- onQueryWriteCompletion(writeFuture);
- }
- });
- }
- }
-
- private void onQueryWriteCompletion(ChannelFuture writeFuture) {
- if (!writeFuture.isSuccess()) {
- setFailure("failed to send a query", writeFuture.cause());
- return;
- }
-
- // Schedule a query timeout task if necessary.
- final long queryTimeoutMillis = parent.queryTimeoutMillis();
- if (queryTimeoutMillis > 0) {
- timeoutFuture = parent.ch.eventLoop().schedule(new Runnable() {
- @Override
- public void run() {
- if (promise.isDone()) {
- // Received a response before the query times out.
- return;
- }
-
- setFailure("query timed out after " + queryTimeoutMillis + " milliseconds", null);
- }
- }, queryTimeoutMillis, TimeUnit.MILLISECONDS);
- }
- }
-
- void finish(AddressedEnvelope extends DnsResponse, InetSocketAddress> envelope) {
- final DnsResponse res = envelope.content();
- if (res.count(DnsSection.QUESTION) != 1) {
- logger.warn("Received a DNS response with invalid number of questions: {}", envelope);
- return;
- }
-
- if (!question().equals(res.recordAt(DnsSection.QUESTION))) {
- logger.warn("Received a mismatching DNS response: {}", envelope);
- return;
- }
-
- setSuccess(envelope);
- }
-
- private void setSuccess(AddressedEnvelope extends DnsResponse, InetSocketAddress> envelope) {
- parent.queryContextManager.remove(nameServerAddr(), id);
-
- // Cancel the timeout task.
- final ScheduledFuture> timeoutFuture = this.timeoutFuture;
- if (timeoutFuture != null) {
- timeoutFuture.cancel(false);
- }
-
- Promise> promise = this.promise;
- if (promise.setUncancellable()) {
- @SuppressWarnings("unchecked")
- AddressedEnvelope castResponse =
- (AddressedEnvelope) envelope.retain();
- promise.setSuccess(castResponse);
- }
- }
-
- private void setFailure(String message, Throwable cause) {
- final InetSocketAddress nameServerAddr = nameServerAddr();
- parent.queryContextManager.remove(nameServerAddr, id);
-
- final StringBuilder buf = new StringBuilder(message.length() + 64);
- buf.append('[')
- .append(nameServerAddr)
- .append("] ")
- .append(message)
- .append(" (no stack trace available)");
-
- final DnsNameResolverException e;
- if (cause != null) {
- e = new DnsNameResolverException(nameServerAddr, question(), buf.toString(), cause);
- } else {
- e = new DnsNameResolverException(nameServerAddr, question(), buf.toString());
- }
-
- promise.tryFailure(e);
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java
deleted file mode 100644
index 9c3946c72f..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import io.netty.util.NetUtil;
-import io.netty.util.collection.IntObjectHashMap;
-import io.netty.util.collection.IntObjectMap;
-import io.netty.util.internal.ThreadLocalRandom;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.Map;
-
-final class DnsQueryContextManager {
-
- /**
- * A map whose key is the DNS server address and value is the map of the DNS query ID and its corresponding
- * {@link DnsQueryContext}.
- */
- final Map> map =
- new HashMap>();
-
- int add(DnsQueryContext qCtx) {
- final IntObjectMap contexts = getOrCreateContextMap(qCtx.nameServerAddr());
-
- int id = ThreadLocalRandom.current().nextInt(1, 65536);
- final int maxTries = 65535 << 1;
- int tries = 0;
-
- synchronized (contexts) {
- for (;;) {
- if (!contexts.containsKey(id)) {
- contexts.put(id, qCtx);
- return id;
- }
-
- id = id + 1 & 0xFFFF;
-
- if (++tries >= maxTries) {
- throw new IllegalStateException("query ID space exhausted: " + qCtx.question());
- }
- }
- }
- }
-
- DnsQueryContext get(InetSocketAddress nameServerAddr, int id) {
- final IntObjectMap contexts = getContextMap(nameServerAddr);
- final DnsQueryContext qCtx;
- if (contexts != null) {
- synchronized (contexts) {
- qCtx = contexts.get(id);
- }
- } else {
- qCtx = null;
- }
-
- return qCtx;
- }
-
- DnsQueryContext remove(InetSocketAddress nameServerAddr, int id) {
- final IntObjectMap contexts = getContextMap(nameServerAddr);
- if (contexts == null) {
- return null;
- }
-
- synchronized (contexts) {
- return contexts.remove(id);
- }
- }
-
- private IntObjectMap getContextMap(InetSocketAddress nameServerAddr) {
- synchronized (map) {
- return map.get(nameServerAddr);
- }
- }
-
- private IntObjectMap getOrCreateContextMap(InetSocketAddress nameServerAddr) {
- synchronized (map) {
- final IntObjectMap contexts = map.get(nameServerAddr);
- if (contexts != null) {
- return contexts;
- }
-
- final IntObjectMap newContexts = new IntObjectHashMap();
- final InetAddress a = nameServerAddr.getAddress();
- final int port = nameServerAddr.getPort();
- map.put(nameServerAddr, newContexts);
-
- if (a instanceof Inet4Address) {
- // Also add the mapping for the IPv4-compatible IPv6 address.
- final Inet4Address a4 = (Inet4Address) a;
- if (a4.isLoopbackAddress()) {
- map.put(new InetSocketAddress(NetUtil.LOCALHOST6, port), newContexts);
- } else {
- map.put(new InetSocketAddress(toCompatAddress(a4), port), newContexts);
- }
- } else if (a instanceof Inet6Address) {
- // Also add the mapping for the IPv4 address if this IPv6 address is compatible.
- final Inet6Address a6 = (Inet6Address) a;
- if (a6.isLoopbackAddress()) {
- map.put(new InetSocketAddress(NetUtil.LOCALHOST4, port), newContexts);
- } else if (a6.isIPv4CompatibleAddress()) {
- map.put(new InetSocketAddress(toIPv4Address(a6), port), newContexts);
- }
- }
-
- return newContexts;
- }
- }
-
- private static Inet6Address toCompatAddress(Inet4Address a4) {
- byte[] b4 = a4.getAddress();
- byte[] b6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b4[0], b4[1], b4[2], b4[3] };
- try {
- return (Inet6Address) InetAddress.getByAddress(b6);
- } catch (UnknownHostException e) {
- throw new Error(e);
- }
- }
-
- private static Inet4Address toIPv4Address(Inet6Address a6) {
- byte[] b6 = a6.getAddress();
- byte[] b4 = { b6[12], b6[13], b6[14], b6[15] };
- try {
- return (Inet4Address) InetAddress.getByAddress(b4);
- } catch (UnknownHostException e) {
- throw new Error(e);
- }
- }
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java
deleted file mode 100644
index 2e806ef787..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStream.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2015 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import java.net.InetSocketAddress;
-
-/**
- * An infinite stream of DNS server addresses.
- */
-public interface DnsServerAddressStream {
- /**
- * Retrieves the next DNS server address from the stream.
- */
- InetSocketAddress next();
-}
diff --git a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java b/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java
deleted file mode 100644
index 0d83fd9eff..0000000000
--- a/netty-bp/resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddresses.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright 2014 The Netty Project
- *
- * The Netty Project licenses this file to you under the Apache License,
- * version 2.0 (the "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations
- * under the License.
- */
-
-package io.netty.resolver.dns;
-
-import io.netty.util.internal.InternalThreadLocalMap;
-import io.netty.util.internal.logging.InternalLogger;
-import io.netty.util.internal.logging.InternalLoggerFactory;
-
-import java.lang.reflect.Method;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Provides an infinite sequence of DNS server addresses to {@link DnsNameResolver}.
- */
-@SuppressWarnings("IteratorNextCanNotThrowNoSuchElementException")
-public abstract class DnsServerAddresses {
-
- private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsServerAddresses.class);
-
- private static final List DEFAULT_NAME_SERVER_LIST;
- private static final InetSocketAddress[] DEFAULT_NAME_SERVER_ARRAY;
- private static final DnsServerAddresses DEFAULT_NAME_SERVERS;
-
- static {
- final int DNS_PORT = 53;
- final List defaultNameServers = new ArrayList(2);
- try {
- Class> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
- Method open = configClass.getMethod("open");
- Method nameservers = configClass.getMethod("nameservers");
- Object instance = open.invoke(null);
-
- @SuppressWarnings("unchecked")
- final List list = (List) nameservers.invoke(instance);
- for (String a: list) {
- if (a != null) {
- defaultNameServers.add(new InetSocketAddress(InetAddress.getByName(a), DNS_PORT));
- }
- }
- } catch (Exception ignore) {
- // Failed to get the system name server list.
- // Will add the default name servers afterwards.
- }
-
- if (!defaultNameServers.isEmpty()) {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "Default DNS servers: {} (sun.net.dns.ResolverConfiguration)", defaultNameServers);
- }
- } else {
- Collections.addAll(
- defaultNameServers,
- new InetSocketAddress("8.8.8.8", DNS_PORT),
- new InetSocketAddress("8.8.4.4", DNS_PORT));
-
- if (logger.isWarnEnabled()) {
- logger.warn(
- "Default DNS servers: {} (Google Public DNS as a fallback)", defaultNameServers);
- }
- }
-
- DEFAULT_NAME_SERVER_LIST = Collections.unmodifiableList(defaultNameServers);
- DEFAULT_NAME_SERVER_ARRAY = defaultNameServers.toArray(new InetSocketAddress[defaultNameServers.size()]);
- DEFAULT_NAME_SERVERS = sequential(DEFAULT_NAME_SERVER_ARRAY);
- }
-
- /**
- * Returns the list of the system DNS server addresses. If it failed to retrieve the list of the system DNS server
- * addresses from the environment, it will return {@code "8.8.8.8"} and {@code "8.8.4.4"}, the addresses of the
- * Google public DNS servers.
- */
- public static List defaultAddressList() {
- return DEFAULT_NAME_SERVER_LIST;
- }
-
- /**
- * Returns the {@link DnsServerAddresses} that yields the system DNS server addresses sequentially. If it failed to
- * retrieve the list of the system DNS server addresses from the environment, it will use {@code "8.8.8.8"} and
- * {@code "8.8.4.4"}, the addresses of the Google public DNS servers.
- *
- * This method has the same effect with the following code:
- *