View Javadoc
1   /*
2    * Copyright 2019 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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  
22  import java.net.SocketAddress;
23  
24  public final class TcpDnsResponseDecoder extends LengthFieldBasedFrameDecoder {
25  
26      private final DnsResponseDecoder<SocketAddress> responseDecoder;
27  
28      /**
29       * Creates a new decoder with {@linkplain DnsRecordDecoder#DEFAULT the default record decoder}.
30       */
31      public TcpDnsResponseDecoder() {
32          this(DnsRecordDecoder.DEFAULT, 64 * 1024);
33      }
34  
35      /**
36       * Creates a new decoder with the specified {@code recordDecoder} and {@code maxFrameLength}
37       */
38      public TcpDnsResponseDecoder(DnsRecordDecoder recordDecoder, int maxFrameLength) {
39          // Length is two octets as defined by RFC-7766
40          // See https://tools.ietf.org/html/rfc7766#section-8
41          super(maxFrameLength, 0, 2, 0, 2);
42  
43          this.responseDecoder = new DnsResponseDecoder<SocketAddress>(recordDecoder) {
44              @Override
45              protected DnsResponse newResponse(SocketAddress sender, SocketAddress recipient,
46                                                int id, DnsOpCode opCode, DnsResponseCode responseCode) {
47                  return new DefaultDnsResponse(id, opCode, responseCode);
48              }
49          };
50      }
51  
52      @Override
53      protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
54          ByteBuf frame = (ByteBuf) super.decode(ctx, in);
55          if (frame == null) {
56              return null;
57          }
58  
59          try {
60              return responseDecoder.decode(ctx.channel().remoteAddress(), ctx.channel().localAddress(), frame.slice());
61          } finally {
62              frame.release();
63          }
64      }
65  
66      @Override
67      protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
68          return buffer.copy(index, length);
69      }
70  }