1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.dns;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
21 import io.netty.util.internal.UnstableApi;
22
23 import java.net.SocketAddress;
24
25 @UnstableApi
26 public final class TcpDnsResponseDecoder extends LengthFieldBasedFrameDecoder {
27
28 private final DnsResponseDecoder<SocketAddress> responseDecoder;
29
30
31
32
33 public TcpDnsResponseDecoder() {
34 this(DnsRecordDecoder.DEFAULT, 64 * 1024);
35 }
36
37
38
39
40 public TcpDnsResponseDecoder(DnsRecordDecoder recordDecoder, int maxFrameLength) {
41
42
43 super(maxFrameLength, 0, 2, 0, 2);
44
45 this.responseDecoder = new DnsResponseDecoder<SocketAddress>(recordDecoder) {
46 @Override
47 protected DnsResponse newResponse(SocketAddress sender, SocketAddress recipient,
48 int id, DnsOpCode opCode, DnsResponseCode responseCode) {
49 return new DefaultDnsResponse(id, opCode, responseCode);
50 }
51 };
52 }
53
54 @Override
55 protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
56 ByteBuf frame = (ByteBuf) super.decode(ctx, in);
57 if (frame == null) {
58 return null;
59 }
60
61 try {
62 return responseDecoder.decode(ctx.channel().remoteAddress(), ctx.channel().localAddress(), frame.slice());
63 } finally {
64 frame.release();
65 }
66 }
67
68 @Override
69 protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
70 return buffer.copy(index, length);
71 }
72 }